<template>
  <div class="timeline-container">
    <el-card class="timeline-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><Calendar /></el-icon>
            项目实施周期
            <el-tag v-if="projectData.project_name" type="primary" size="small" style="margin-left: 10px;">
              {{ projectData.project_name }}
            </el-tag>
          </h2>
          <p class="description">
            管理项目各阶段的计划时间、实际时间和完成情况
            <span v-if="projectData.project_id" style="color: #e6a23c; font-weight: 500;">
              (项目编号: {{ projectData.project_id }})
            </span>
          </p>
        </div>
        <div class="header-actions">
          <el-button v-if="hasPermission" type="primary" @click="openDialog()" class="create-btn">
            <el-icon><Plus /></el-icon>
            添加阶段
          </el-button>
          <el-button v-if="hasPermission" type="success" @click="syncWeightData">
            <el-icon><Refresh /></el-icon>
            同步权重
          </el-button>
          <el-button v-if="hasPermission" type="warning" @click="refreshTimePeriods">
            <el-icon><Calendar /></el-icon>
            刷新周期
          </el-button>
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索阶段编码、阶段说明..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterStatus" placeholder="状态筛选" clearable>
          <el-option label="已完成" value="completed" />
          <el-option label="进行中" value="inProgress" />
          <el-option label="待开始" value="pending" />
          <el-option label="已延期" value="delayed" />
        </el-select>
      </div>

      <!-- 项目周期计划表格 -->
      <div class="schedule-table-section">
        <div class="table-header">
          <div class="table-title">
          <h3>项目周期计划详情</h3>
          </div>
          <div class="table-actions">
            <el-button 
              v-if="hasPermission"
              type="primary" 
              @click="saveAllProgress" 
              :loading="savingProgress"
              size="large"
              class="save-progress-btn"
            >
              <el-icon><Check /></el-icon>
              保存所有进度
            </el-button>
          </div>
        </div>
        
        <!-- 权重状态提示 -->
        <div v-if="weightStatusMessage" class="weight-status-tip">
          <el-alert
            :title="weightStatusMessage"
            :type="weightStatusType"
            :closable="false"
            show-icon
          />
        </div>
        
        <!-- 响应式表格容器 -->
        <div class="table-responsive-container">
          <el-table 
            :data="pagedPeriodicPlanList" 
            stripe 
            border 
            v-loading="loading" 
            class="periodic-table responsive-table"
            :header-cell-style="{ 
              background: '#f5f7fa', 
              color: '#606266',
              fontSize: '14px',
              fontWeight: '500'
            }"
            :cell-style="{ fontSize: '13px' }"
          >
            <el-table-column prop="phase_cycle" label="项目周期" min-width="120" max-width="150" />
            <el-table-column prop="phase_code" label="阶段编码" min-width="120" max-width="150" />
            <el-table-column prop="phase_desc" label="阶段说明" min-width="180" max-width="250" show-overflow-tooltip />
            <el-table-column prop="weight" label="权重(%)" width="80" min-width="80">
              <template #default="scope">
                <span class="weight-text">{{ scope.row.weight }}%</span>
              </template>
            </el-table-column>
            
            <!-- 动态生成的时间列 - 响应式显示 -->
            <el-table-column 
              v-for="date in timePeriods" 
              :key="date" 
              :label="formatDate(date)" 
              :width="90"
              :min-width="90"
              :max-width="120"
              align="center"
            >
              <template #header>
                <div class="date-header">
                  <div class="date-label">{{ formatDate(date) }}</div>
                </div>
              </template>
              <template #default="scope">
                <div class="progress-cell-responsive">
                  <!-- 完成率输入框 -->
                  <el-input
                    v-model="scope.row.progress[date].completion_rate"
                    size="small"
                    class="completion-input"
                    :disabled="!hasPermission"
                    @change="handleProgressChange(scope.row, date)"
                    @blur="validateCompletionRate(scope.row, date)"
                  >
                    <template #suffix>%</template>
                  </el-input>
                  <!-- 完成权重显示 -->
                  <div class="completed-weight-responsive">
                    {{ scope.row.progress[date].completed_weight || '0.0' }}
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <!-- 操作列 -->
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button size="small" type="primary" @click="viewPhaseDetail(scope.row)">
                    <el-icon><View /></el-icon>
                    查看
                  </el-button>
                  <el-button v-if="hasPermission" size="small" type="warning" @click="editPhase(scope.row)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页控件 -->
        <div class="pagination-section">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredPeriodicPlanList.length"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :page-sizes="[5, 10, 20, 50]"
            :pager-count="5"
            style="margin-top: 16px;"
          />
        </div>
        
        <!-- 阶段完成情况统计 -->
        <div class="phase-stats-section">
          <div class="stats-header">
            <h4 class="stats-title">
              <el-icon class="stats-icon"><DataAnalysis /></el-icon>
              阶段完成情况统计
            </h4>
            <div class="stats-subtitle">基于各阶段最高完成率的项目进度分析</div>
          </div>
          
          <div class="phase-stats-container">
            <!-- 项目总体进度卡片 -->
            <div class="phase-stats-summary">
              <div class="summary-header">
                <div class="summary-title-section">
                  <el-icon class="summary-icon"><TrendCharts /></el-icon>
                  <span class="summary-title">项目总体进度</span>
              </div>
                <div class="summary-progress">
                  <div class="progress-circle">
                    <span class="progress-value">{{ getProjectTotalProgress() }}%</span>
                    <span class="progress-label">总进度</span>
                  </div>
                </div>
              </div>
              
              <div class="summary-content">
                <div class="summary-grid">
                  <div class="summary-item">
                    <div class="item-icon">
                      <el-icon><TrendCharts /></el-icon>
                    </div>
                    <div class="item-content">
                      <span class="item-label">总权重</span>
                      <span class="item-value">{{ totalWeight }}%</span>
                    </div>
                  </div>
                  
                  <div class="summary-item">
                    <div class="item-icon">
                      <el-icon><Check /></el-icon>
                    </div>
                    <div class="item-content">
                      <span class="item-label">已完成权重</span>
                      <span class="item-value">{{ getCompletedTotalWeight() }}%</span>
                    </div>
                  </div>
                  
                  <div class="summary-item">
                    <div class="item-icon">
                      <el-icon><Star /></el-icon>
                    </div>
                    <div class="item-content">
                      <span class="item-label">完成阶段</span>
                      <span class="item-value">{{ getCompletedPhasesCount() }}个</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 各阶段完成情况表格 -->
            <div class="phase-stats-details">
              <div class="details-header">
                <div class="details-title-section">
                  <el-icon class="details-icon"><List /></el-icon>
                  <span class="details-title">各阶段完成情况</span>
                </div>
                <div class="details-count">
                  共 {{ getSimplifiedPhaseStats().length }} 个阶段
                </div>
              </div>
              
              <!-- 分页控件 -->
              <div class="phase-stats-pagination" v-if="getSimplifiedPhaseStats().length > 5">
                <el-pagination
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="getSimplifiedPhaseStats().length"
                  :page-size="phaseStatsPageSize"
                  :current-page="phaseStatsCurrentPage"
                  @current-change="handlePhaseStatsCurrentChange"
                  @size-change="handlePhaseStatsSizeChange"
                  :page-sizes="getAdaptivePageSizes()"
                  :pager-count="5"
                  small
                />
              </div>
              
              <div class="phase-stats-table">
                <div class="table-header">
                  <div class="header-cell phase-code-header">阶段编码</div>
                  <div class="header-cell phase-desc-header">阶段说明</div>
                  <div class="header-cell phase-weight-header">权重</div>
                  <div class="header-cell phase-completion-header">完成率</div>
                  <div class="header-cell phase-contribution-header">贡献度</div>
                </div>
                
                <div class="table-body">
                  <div 
                    v-for="(stat, index) in getPagedPhaseStats()" 
                    :key="stat.phaseCode"
                    class="table-row"
                    :class="{ 
                      'row-even': index % 2 === 0, 
                      'row-odd': index % 2 === 1,
                      'completed': stat.maxCompletionRate === 100,
                      'warning': stat.maxCompletionRate >= 80 && stat.maxCompletionRate < 100
                    }"
                  >
                    <div class="table-cell phase-code-cell">
                      <el-tag size="small" type="primary">{{ stat.phaseCode }}</el-tag>
                    </div>
                    <div class="table-cell phase-desc-cell">
                      <span class="phase-desc-text" :title="stat.phaseDesc">{{ stat.phaseDesc }}</span>
                    </div>
                    <div class="table-cell phase-weight-cell">
                      <span class="weight-badge">{{ stat.weight }}%</span>
                    </div>
                    <div class="table-cell phase-completion-cell">
                      <el-progress 
                        :percentage="stat.maxCompletionRate" 
                        :color="getProgressColor(stat.maxCompletionRate)"
                        :stroke-width="8"
                        :show-text="false"
                      />
                      <span class="completion-text">{{ stat.maxCompletionRate }}%</span>
                    </div>
                    <div class="table-cell phase-contribution-cell">
                      <span class="contribution-badge">{{ stat.contribution }}%</span>
                    </div>
                  </div>
                  
                  <div v-if="getPagedPhaseStats().length === 0" class="no-data">
                    <el-empty description="暂无进度数据" :image-size="60" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 详细统计说明 -->
        <div class="stats-explanation">
          <el-alert
            title="统计说明"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="explanation-content">
                <p><strong>总进度</strong>：基于各阶段最高完成率的项目整体进度</p>
                <p><strong>阶段编码</strong>：项目阶段的唯一标识</p>
                <p><strong>阶段说明</strong>：该阶段的具体工作内容描述</p>
                <p><strong>权重</strong>：该阶段在项目中的重要性占比</p>
                <p><strong>完成率</strong>：该阶段在所有周期中的最高完成百分比</p>
                <p><strong>贡献度</strong>：权重 × 该阶段最高完成率 = 该阶段在项目的总完成率</p>
                <p class="example">示例：阶段权重20%，最高完成率100%，则该阶段贡献20%到项目总进度</p>
                <p class="note">注意：统计时自动跳过权重为0或完成率为0的阶段，确保统计的科学性和准确性</p>
              </div>
            </template>
          </el-alert>
        </div>
      </div>

     
    </el-card>

    <!-- 项目实施周期创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑项目阶段' : '添加项目阶段'"
      width="800px"
      align-center
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="project_id">
              <el-input v-model="form.project_id" placeholder="项目编号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阶段编码" prop="phase_code">
              <el-input v-model="form.phase_code" placeholder="请输入阶段编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="阶段说明" prop="phase_desc">
          <el-input v-model="form.phase_desc" type="textarea" :rows="2" placeholder="请输入阶段说明" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="planned_start">
              <el-date-picker
                v-model="form.planned_start"
                type="date"
                placeholder="选择计划开始时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="planned_end">
              <el-date-picker
                v-model="form.planned_end"
                type="date"
                placeholder="选择计划结束时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实际开始时间" prop="actual_start">
              <el-date-picker
                v-model="form.actual_start"
                type="date"
                placeholder="选择实际开始时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际结束时间" prop="actual_end">
              <el-date-picker
                v-model="form.actual_end"
                type="date"
                placeholder="选择实际结束时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="阶段权重" prop="weight">
              <el-input-number
                v-model="form.weight"
                :min="0"
                :max="100"
                :precision="2"
                style="width: 100%"
                placeholder="请输入权重"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成率" prop="completion_rate">
              <el-input-number
                v-model="form.completion_rate"
                :min="0"
                :max="100"
                :precision="0"
                style="width: 100%"
                placeholder="请输入完成率"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注信息（选填）" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>

    <!-- 项目阶段详情查看对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="项目阶段详情"
      width="800px"
      align-center
      :close-on-click-modal="true"
    >
      <div v-if="selectedPhase" class="phase-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目编号">
            {{ selectedPhase.project_id }}
          </el-descriptions-item>
          <el-descriptions-item label="阶段编码">
            {{ selectedPhase.phase_code }}
          </el-descriptions-item>
          <el-descriptions-item label="阶段说明" :span="2">
            {{ selectedPhase.phase_desc }}
          </el-descriptions-item>
          <el-descriptions-item label="项目周期">
            {{ selectedPhase.phase_cycle }}
          </el-descriptions-item>
          <el-descriptions-item label="阶段权重">
            {{ selectedPhase.weight }}%
          </el-descriptions-item>
          <el-descriptions-item label="计划开始时间">
            {{ selectedPhase.planned_start || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="计划结束时间">
            {{ selectedPhase.planned_end || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="实际开始时间">
            {{ selectedPhase.actual_start || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="实际结束时间">
            {{ selectedPhase.actual_end || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="完成率">
            {{ selectedPhase.completion_rate || 0 }}%
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedPhase.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 进度详情 -->
        <div class="progress-detail" style="margin-top: 20px;">
          <h4>各周期进度详情</h4>
          <el-table :data="getProgressDetailData()" border stripe>
            <el-table-column prop="date" label="周期" width="120">
              <template #default="scope">
                {{ formatDate(scope.row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="completion_rate" label="完成率" width="100">
              <template #default="scope">
                {{ scope.row.completion_rate }}%
              </template>
            </el-table-column>
            <el-table-column prop="completed_weight" label="完成权重" width="120">
              <template #default="scope">
                {{ scope.row.completed_weight }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getProgressStatusType(scope.row.completion_rate)" size="small">
                  {{ getProgressStatusText(scope.row.completion_rate) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button v-if="hasPermission" type="primary" @click="editFromDetail">编辑</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar, Refresh, Plus, Search, Edit, Delete, Star, Check, View, DataAnalysis, TrendCharts , List } from '@element-plus/icons-vue'
import { getProjectScheduleListByProjectId, createProjectSchedule, updateProjectSchedule, deleteProjectSchedule } from '../../api/projectSchedule'
import { getProjectPhaseWeightListByProjectId } from '../../api/projectPhaseWeight'


// 定义props
const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  projectData: {
    type: Object,
    default: () => ({})
  }
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 检查是否为当前项目的项目经理
const isProjectManager = computed(() => {
  if (!props.projectData || !props.projectData.project_manager) {
    return false
  }
  // 检查当前用户是否为该项目的项目经理
  return currentUser.value.username === props.projectData.project_manager || 
         currentUser.value.userId === props.projectData.project_manager ||
         currentUser.value.id === props.projectData.project_manager
})

// 检查是否有权限操作（只有当前项目的项目经理可以操作）
const hasPermission = computed(() => {
  return isProjectManager.value
})

// 检查是否为管理员（只有管理员可以新增）
const canAdd = computed(() => {
  return isAdmin.value
})

// 响应式数据
const projectScheduleList = ref([])
const periodicPlanList = ref([])
const weightList = ref([])
const loading = ref(false)
const submitLoading = ref(false)
const generatingPlan = ref(false)
const savingProgress = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const selectedPhase = ref(null)
const searchKeyword = ref('')
const filterStatus = ref('')
const formRef = ref()
const weightStatusMessage = ref('')
const weightStatusType = ref('info')

// 分页相关
const pageSize = ref(10)
const currentPage = ref(1)

function handleCurrentChange(val) {
  currentPage.value = val
}
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1 // 切换每页数量时重置到第一页
}

// 阶段统计分页相关
const phaseStatsPageSize = ref(5)
const phaseStatsCurrentPage = ref(1)

function handlePhaseStatsCurrentChange(val) {
  phaseStatsCurrentPage.value = val
}

function handlePhaseStatsSizeChange(val) {
  phaseStatsPageSize.value = val
  phaseStatsCurrentPage.value = 1 // 切换每页数量时重置到第一页
}

// 获取自适应的分页大小选项
function getAdaptivePageSizes() {
  const total = getSimplifiedPhaseStats().length
  if (total <= 10) {
    return [5, 10]
  } else if (total <= 20) {
    return [5, 10, 15]
  } else if (total <= 50) {
    return [5, 10, 20, 30]
  } else {
    return [5, 10, 20, 30, 50]
  }
}

// 获取分页后的阶段统计数据
function getPagedPhaseStats() {
  const stats = getSimplifiedPhaseStats()
  if (stats.length <= 5) {
    return stats
  }
  
  const start = (phaseStatsCurrentPage.value - 1) * phaseStatsPageSize.value
  const end = start + phaseStatsPageSize.value
  return stats.slice(start, end)
}
// 支持搜索和状态筛选的周期计划列表
const filteredPeriodicPlanList = computed(() => {
  let list = periodicPlanList.value
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    list = list.filter(item =>
      item.phase_code.toLowerCase().includes(keyword) ||
      item.phase_desc.toLowerCase().includes(keyword)
    )
  }
  if (filterStatus.value) {
    // 这里只做简单示例，实际可根据你的业务调整
    if (filterStatus.value === 'completed') {
      list = list.filter(item => {
        // 假设每个阶段有一个最新周期的完成率
        const lastDate = timePeriods.value[timePeriods.value.length - 1]
        return item.progress[lastDate]?.completion_rate >= 100
      })
    } else if (filterStatus.value === 'inProgress') {
      const lastDate = timePeriods.value[timePeriods.value.length - 1]
      list = list.filter(item => {
        const rate = item.progress[lastDate]?.completion_rate || 0
        return rate > 0 && rate < 100
      })
    } else if (filterStatus.value === 'pending') {
      const lastDate = timePeriods.value[timePeriods.value.length - 1]
      list = list.filter(item => {
        const rate = item.progress[lastDate]?.completion_rate || 0
        return rate === 0
      })
    } else if (filterStatus.value === 'delayed') {
      // 这里可根据实际业务定义"已延期"
      // 示例：所有周期都未完成
      list = list.filter(item => {
        return Object.values(item.progress).every(p => (p.completion_rate || 0) === 0)
      })
    }
  }
  return list
})
const pagedPeriodicPlanList = computed(() => {
  const data = filteredPeriodicPlanList.value
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return data.slice(start, end)
})

// 分页信息
const paginationInfo = computed(() => {
  const total = filteredPeriodicPlanList.value.length
  const start = (currentPage.value - 1) * pageSize.value + 1
  const end = Math.min(currentPage.value * pageSize.value, total)
  return {
    total,
    start: total > 0 ? start : 0,
    end,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    totalPages: Math.ceil(total / pageSize.value)
  }
})

// 时间周期（动态生成，每两周一个周期）
const timePeriods = ref([])



const form = ref({
  id: null,
  project_id: '',
  phase_code: '',
  phase_desc: '',
  planned_start: '',
  planned_end: '',
  actual_start: '',
  actual_end: '',
  weight: 0,
  completion_rate: 0,
  remark: ''
})

const formRules = {
  project_id: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
  phase_code: [{ required: true, message: '请输入阶段编码', trigger: 'blur' }],
  phase_desc: [{ required: true, message: '请输入阶段说明', trigger: 'blur' }],
  planned_start: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }],
  planned_end: [{ required: true, message: '请选择计划结束时间', trigger: 'change' }],
  weight: [{ required: true, message: '请输入阶段权重', trigger: 'blur' }],
  completion_rate: [{ required: true, message: '请输入完成率', trigger: 'blur' }]
}

// 阶段统计
const scheduleCounts = computed(() => {
  const counts = {
    completed: 0,
    inProgress: 0,
    pending: 0,
    delayed: 0
  }
  
  const currentProjectId = props.projectData.project_id || props.projectId
  const currentProjectSchedule = projectScheduleList.value.filter(schedule => 
    schedule.project_id === currentProjectId
  )
  
  currentProjectSchedule.forEach(item => {
    const completionRate = parseInt(item.completion_rate) || 0
    const today = new Date()
    const plannedEnd = new Date(item.planned_end)
    
    if (completionRate >= 100) {
      counts.completed++
    } else if (completionRate > 0) {
      counts.inProgress++
    } else if (today > plannedEnd) {
      counts.delayed++
    } else {
      counts.pending++
    }
  })
  
  return counts
})

// 总权重
const totalWeight = computed(() => {
  return periodicPlanList.value.reduce((sum, item) => sum + (parseInt(item.weight) || 0), 0)
})

// 格式化日期显示
function formatDate(dateStr) {
  if (!dateStr || dateStr.length !== 8) return '-'
  const year = dateStr.substring(0, 4)
  const month = dateStr.substring(4, 6)
  const day = dateStr.substring(6, 8)
  return `${month}/${day}`
}

// 计算完成权重
function calculateCompletedWeight(item, date) {
  const weight = parseInt(item.weight) || 0
  const completionRate = item.progress[date]?.completion_rate || 0
  return ((weight * completionRate) / 100).toFixed(1)
}

// 重新计算所有阶段的完成权重
function recalculateAllCompletedWeights() {
  console.log('重新计算所有阶段的完成权重...')
  
  periodicPlanList.value.forEach(item => {
    timePeriods.value.forEach(date => {
      const completionRate = parseInt(item.progress[date]?.completion_rate) || 0
      const weight = parseInt(item.weight) || 0
      item.progress[date].completed_weight = ((weight * completionRate) / 100).toFixed(1)
    })
  })
  
  console.log('完成权重重新计算完成')
}

// 获取项目总进度（基于各阶段最高完成率）
function getProjectTotalProgress() {
  try {
    let totalWeight = 0
    let totalCompletedWeight = 0
    
    periodicPlanList.value.forEach(phase => {
      const weight = parseFloat(phase.weight) || 0
      if (weight <= 0) return
      
      totalWeight += weight
      
      // 计算该阶段在所有周期中的最高完成率
      let maxCompletionRate = 0
      timePeriods.value.forEach(date => {
        const progress = phase.progress[date]
        if (progress) {
          const completionRate = parseInt(progress.completion_rate) || 0
          if (completionRate > maxCompletionRate) {
            maxCompletionRate = completionRate
          }
        }
      })
      
      // 该阶段在项目的总完成率 = 权重 × 最高完成率
      totalCompletedWeight += (weight * maxCompletionRate / 100)
    })
    
    if (totalWeight === 0) return '0.0'
    
    const totalProgress = (totalCompletedWeight / totalWeight * 100).toFixed(1)
    return totalProgress
  } catch (error) {
    console.error('获取项目总进度失败:', error)
    return '0.0'
  }
}

// 获取已完成的总权重
function getCompletedTotalWeight() {
  try {
    let totalCompletedWeight = 0
    
    periodicPlanList.value.forEach(phase => {
      const weight = parseFloat(phase.weight) || 0
      if (weight <= 0) return
      
      // 计算该阶段在所有周期中的最高完成率
      let maxCompletionRate = 0
      timePeriods.value.forEach(date => {
        const progress = phase.progress[date]
        if (progress) {
          const completionRate = parseInt(progress.completion_rate) || 0
          if (completionRate > maxCompletionRate) {
            maxCompletionRate = completionRate
          }
        }
      })
      
      // 该阶段在项目的总完成率 = 权重 × 最高完成率
      totalCompletedWeight += (weight * maxCompletionRate / 100)
    })
    
    return totalCompletedWeight.toFixed(1)
  } catch (error) {
    console.error('获取已完成总权重失败:', error)
    return '0.0'
  }
}

// 获取已完成阶段数量
function getCompletedPhasesCount() {
  try {
    let completedCount = 0
    
    periodicPlanList.value.forEach(phase => {
      const weight = parseFloat(phase.weight) || 0
      if (weight <= 0) return
      
      // 检查该阶段是否完成（100%）
      let isCompleted = false
      timePeriods.value.forEach(date => {
        const progress = phase.progress[date]
        if (progress && parseInt(progress.completion_rate) === 100) {
          isCompleted = true
        }
      })
      
      if (isCompleted) {
        completedCount++
      }
    })
    
    return completedCount
  } catch (error) {
    console.error('获取已完成阶段数量失败:', error)
    return 0
  }
}

// 获取简化的阶段统计（快速版本）
function getSimplifiedPhaseStats() {
  try {
    const stats = []
    
    periodicPlanList.value.forEach(phase => {
      const weight = parseFloat(phase.weight) || 0
      if (weight <= 0) return
      
      // 计算该阶段在所有周期中的最高完成率
      let maxCompletionRate = 0
      timePeriods.value.forEach(date => {
        const progress = phase.progress[date]
        if (progress) {
          const completionRate = parseInt(progress.completion_rate) || 0
          if (completionRate > maxCompletionRate) {
            maxCompletionRate = completionRate
          }
        }
      })
      
      // 跳过完成率为0的阶段
      if (maxCompletionRate <= 0) return
      
      // 计算该阶段对项目总进度的贡献
      // 贡献度 = 权重 × 该阶段最高完成率
      const completedWeight = (weight * maxCompletionRate / 100)
      const contribution = completedWeight.toFixed(1)
      
      stats.push({
        phaseCode: phase.phase_code,
        phaseDesc: phase.phase_desc,
        weight: weight,
        maxCompletionRate: maxCompletionRate,
        contribution: contribution
      })
    })
    
    // 按贡献度排序
    stats.sort((a, b) => parseFloat(b.contribution) - parseFloat(a.contribution))
    
    return stats
  } catch (error) {
    console.error('获取简化阶段统计失败:', error)
    return []
  }
}

// 获取进度条颜色
function getProgressColor(completionRate) {
  const rate = parseInt(completionRate) || 0
  if (rate >= 100) return '#67C23A' // 绿色 - 已完成
  if (rate >= 80) return '#E6A23C'  // 橙色 - 接近完成
  if (rate >= 50) return '#409EFF'  // 蓝色 - 进行中
  if (rate > 0) return '#F56C6C'    // 红色 - 刚开始
  return '#C0C4CC'                   // 灰色 - 未开始
}

// 生成清晰的阶段完成统计信息（修复版本）
function generatePhaseCompletionStats() {
  try {
    const stats = {
      totalProgress: 0,
      completedPhases: 0,
      inProgressPhases: 0,
      phaseDetails: [],
      periodStats: {}
    }
    
    if (!periodicPlanList.value || periodicPlanList.value.length === 0) {
      return stats
    }
    
    // 按时间周期统计
    timePeriods.value.forEach(date => {
      const periodData = {
        date: date,
        totalWeight: 0,
        completedWeight: 0,
        totalProgress: 0,
        phases: []
      }
      
      // 第一遍：计算总权重和总完成权重
      periodicPlanList.value.forEach(phase => {
        const weight = parseFloat(phase.weight) || 0
        const progress = phase.progress[date]
        
        // 跳过权重为0或没有进度数据的阶段
        if (weight <= 0 || !progress) {
          return
        }
        
        const completionRate = parseInt(progress.completion_rate) || 0
        
        // 跳过完成率为0的阶段
        if (completionRate <= 0) {
          return
        }
        
        periodData.totalWeight += weight
        periodData.completedWeight += (weight * completionRate / 100)
      })
      
      // 第二遍：生成阶段详情
      periodicPlanList.value.forEach(phase => {
        const weight = parseFloat(phase.weight) || 0
        const progress = phase.progress[date]
        
        // 跳过权重为0或没有进度数据的阶段
        if (weight <= 0 || !progress) {
          return
        }
        
        const completionRate = parseInt(progress.completion_rate) || 0
        
        // 跳过完成率为0的阶段
        if (completionRate <= 0) {
          return
        }
        
      const completedWeight = (weight * completionRate / 100)
      
        // 修复：贡献度应该是该阶段完成的部分占总进度的百分比
        // 总进度 = 所有阶段完成权重的总和
        const totalCompletedWeight = periodData.completedWeight
        const contribution = totalCompletedWeight > 0 ? ((completedWeight / totalCompletedWeight) * 100).toFixed(1) : '0.0'
        
        periodData.phases.push({
          phaseCode: phase.phase_code,
          phaseDesc: phase.phase_desc,
        completionRate: completionRate,
        weight: weight,
          completedWeight: completedWeight,
          contribution: contribution
        })
      })
      
      // 计算总进度百分比
      if (periodData.totalWeight > 0) {
        periodData.totalProgress = ((periodData.completedWeight / periodData.totalWeight) * 100).toFixed(1)
      }
      
      // 按贡献度排序
      periodData.phases.sort((a, b) => parseFloat(b.contribution) - parseFloat(a.contribution))
      
      stats.periodStats[date] = periodData
    })
    
    // 计算整体统计（修复：基于当前周期的实际完成情况）
    let totalWeight = 0
    let totalCompletedWeight = 0
    
    // 使用最后一个有数据的周期来计算整体统计
    const lastPeriodWithData = Object.keys(stats.periodStats).find(date => {
      const period = stats.periodStats[date]
      return period && period.phases.length > 0
    })
    
    if (lastPeriodWithData) {
      const lastPeriod = stats.periodStats[lastPeriodWithData]
      totalWeight = lastPeriod.totalWeight
      totalCompletedWeight = lastPeriod.completedWeight
      stats.totalProgress = lastPeriod.totalProgress
      
      // 统计阶段状态
      periodicPlanList.value.forEach(phase => {
        const weight = parseFloat(phase.weight) || 0
        if (weight <= 0) return
        
        // 检查该阶段在最后一个周期是否完成
        const progress = phase.progress[lastPeriodWithData]
        if (progress) {
          const completionRate = parseInt(progress.completion_rate) || 0
          if (completionRate >= 100) {
            stats.completedPhases++
          } else if (completionRate > 0) {
            stats.inProgressPhases++
          }
        }
      })
    }
    
    return stats
  } catch (error) {
    console.error('生成阶段完成统计信息失败:', error)
    return {
      totalProgress: 0,
      completedPhases: 0,
      inProgressPhases: 0,
      phaseDetails: [],
      periodStats: {}
    }
  }
}

// 优化：减少接口调用的统计方法
function getOptimizedStats() {
  try {
    // 直接使用前端数据，不调用接口
    const stats = generatePhaseCompletionStats()
    
    // 格式化显示信息
    const displayStats = {
      totalProgress: stats.totalProgress,
      completedCount: stats.completedPhases,
      inProgressCount: stats.inProgressPhases,
      periods: []
    }
    
    // 处理每个时间周期的显示
    timePeriods.value.forEach(date => {
      const period = stats.periodStats[date]
      if (period && period.phases.length > 0) {
        const formattedDate = formatDate(date)
        
        displayStats.periods.push({
          date: date,
          formattedDate: formattedDate,
          totalProgress: period.totalProgress,
          activePhaseCount: period.phases.length,
          phases: period.phases.map(phase => ({
            code: phase.phaseCode,
            desc: phase.phaseDesc,
            completion: phase.completionRate + '%',
            weight: phase.weight + '%',
            contribution: phase.contribution + '%',
            isCompleted: phase.completionRate === 100
          }))
        })
      }
    })
    
    return { stats, displayStats }
  } catch (error) {
    console.error('获取优化统计信息失败:', error)
    return null
  }
}

// 显示优化后的统计信息（减少接口调用）
function displayOptimizedStats() {
  try {
    const result = getOptimizedStats()
    if (!result) {
      console.warn('无法获取统计信息')
      return
    }
    
    const { stats, displayStats } = result
    
    console.log('=== 优化后的阶段完成统计 ===')
    console.log(`项目总进度: ${stats.totalProgress}% (已完成: ${stats.completedPhases}个阶段, 进行中: ${stats.inProgressPhases}个阶段)`)
    console.log('')
    
    displayStats.periods.forEach(period => {
      console.log(`${period.formattedDate} - 总进度: ${period.totalProgress}%`)
      period.phases.forEach(phase => {
        console.log(`  ${phase.code}: ${phase.completion}完成, 权重${phase.weight}, 贡献${phase.contribution}%`)
      })
      console.log('')
    })
    
    console.log('=== 统计详情 ===')
    Object.keys(stats.periodStats).forEach(date => {
      const period = stats.periodStats[date]
      if (period.phases.length > 0) {
        console.log(`${formatDate(date)} 统计:`, {
          总权重: period.totalWeight,
          已完成权重: period.completedWeight,
          总进度: period.totalProgress + '%',
          阶段数量: period.phases.length,
          阶段详情: period.phases.map(p => ({
            阶段: p.phaseCode,
            完成率: p.completionRate + '%',
            权重: p.weight + '%',
            贡献: p.contribution + '%'
          }))
        })
      }
    })
    
    return { stats, displayStats }
  } catch (error) {
    console.error('显示优化后的统计信息失败:', error)
    return null
  }
}

// 获取界面显示的统计信息（优化版本）
function getDisplayStats() {
  try {
    const result = getOptimizedStats()
    if (!result) {
      return {
        totalProgress: '0',
        completedCount: 0,
        inProgressCount: 0,
        periods: []
      }
    }
    
    const { stats, displayStats } = result
    return displayStats
  } catch (error) {
    console.error('获取界面显示统计信息失败:', error)
    return {
      totalProgress: '0',
      completedCount: 0,
      inProgressCount: 0,
      periods: []
    }
  }
}

// 在数据更新后自动刷新统计信息（优化版本）
function refreshStatsAfterUpdate() {
  // 延迟执行，确保数据已更新
  setTimeout(() => {
    displayOptimizedStats()
  }, 100)
}

// 过滤后的阶段列表
const filteredScheduleList = computed(() => {
  const currentProjectId = props.projectData.project_id || props.projectId
  
  let filtered = projectScheduleList.value.filter(schedule => 
    schedule.project_id === currentProjectId
  )
  
  // 按搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(schedule => 
      schedule.phase_code.toLowerCase().includes(keyword) ||
      schedule.phase_desc.toLowerCase().includes(keyword)
    )
  }
  
  // 按状态过滤
  if (filterStatus.value) {
    filtered = filtered.filter(schedule => {
      const completionRate = parseInt(schedule.completion_rate) || 0
      const today = new Date()
      const plannedEnd = new Date(schedule.planned_end)
      
      switch (filterStatus.value) {
        case 'completed':
          return completionRate >= 100
        case 'inProgress':
          return completionRate > 0 && completionRate < 100
        case 'pending':
          return completionRate === 0 && today <= plannedEnd
        case 'delayed':
          return today > plannedEnd
        default:
          return true
      }
    })
  }
  
  return filtered
})

// 获取进度条状态
function getProgressStatus(completionRate) {
  const rate = parseInt(completionRate) || 0
  if (rate >= 100) return 'success'
  if (rate >= 80) return 'warning'
  if (rate >= 50) return ''
  return 'exception'
}

// 检查权重数据状态
async function checkWeightDataStatus() {
  const currentProjectId = props.projectData.project_id || props.projectId
  if (!currentProjectId) {
    return { hasData: false, message: '请先选择项目' }
  }

  try {
    const weightData = await getProjectPhaseWeightListByProjectId(currentProjectId)
    let weights = []
    if (Array.isArray(weightData)) {
      weights = weightData
    } else if (weightData && Array.isArray(weightData.data)) {
      weights = weightData.data
    } else if (weightData && Array.isArray(weightData.records)) {
      weights = weightData.records
    }

    if (weights.length === 0) {
      return { 
        hasData: false, 
        message: '项目尚未配置权重，请先在权重设置页面配置项目权重' 
      }
    }

    const totalWeight = weights.reduce((sum, item) => sum + (parseInt(item.weight) || 0), 0)
    if (totalWeight !== 100) {
      return { 
        hasData: true, 
        message: `权重总和为${totalWeight}%，建议调整为100%` 
      }
    }

    return { hasData: true, message: '权重配置正确' }
  } catch (error) {
    console.error('检查权重数据失败:', error)
    return { hasData: false, message: '检查权重数据失败，请重试' }
  }
}

// 检查并更新周期计划
async function checkAndUpdatePeriodicPlan(weights) {
  const currentProjectId = props.projectData.project_id || props.projectId
  if (!currentProjectId) return

  console.log('检查周期计划与权重匹配情况...')
  console.log('权重数据:', weights)
  
  // 初始化时间周期（如果还没有生成）
  if (timePeriods.value.length === 0) {
    initializeTimePeriods()
  } else {
    // 如果已有时间周期，检查是否需要添加新的周期
    generateTimePeriods()
  }
  
  // 获取现有的周期计划数据
  const existingSchedules = await getProjectScheduleListByProjectId(currentProjectId)
  console.log('现有周期计划数据:', existingSchedules)
  
  const existingScheduleMap = new Map()
  existingSchedules.forEach(schedule => {
    existingScheduleMap.set(schedule.phase_code, schedule)
  })
  
  let hasChanges = false
  const planData = []
  
  // 检查每个权重项
  for (const weight of weights) {
    const phaseCode = weight.phase_code
    const existingSchedule = existingScheduleMap.get(phaseCode)
    
    if (existingSchedule) {
      // 已存在：检查是否需要更新权重
      const currentWeight = parseInt(existingSchedule.weight) || 0
      const newWeight = parseInt(weight.weight) || 0
      
      if (currentWeight !== newWeight || existingSchedule.phase_desc !== weight.phase_desc) {
        // 权重或描述有变化，需要更新
        const updatedSchedule = {
          ...existingSchedule,
          weight: newWeight,
          phase_desc: weight.phase_desc
        }
        
        // 确保progress字段是字符串格式
        if (updatedSchedule.progress && typeof updatedSchedule.progress !== 'string') {
          updatedSchedule.progress = JSON.stringify(updatedSchedule.progress)
        }
        
        // 更新到数据库
        await updateProjectSchedule(existingSchedule.id, updatedSchedule)
        planData.push(updatedSchedule)
        hasChanges = true
        
        console.log(`更新阶段权重: ${phaseCode}, 权重: ${currentWeight}% -> ${newWeight}%`)
        
        // 如果权重发生变化，重新计算所有时间周期的完成权重
        if (currentWeight !== newWeight) {
          console.log(`权重变化，重新计算完成权重: ${phaseCode}`)
          // 这里可以添加重新计算完成权重的逻辑
        }
      } else {
        // 无需更新，直接使用现有数据
        planData.push(existingSchedule)
        console.log(`阶段无需更新: ${phaseCode}`)
      }
    } else {
      // 不存在：创建新的周期计划
      console.log(`创建新阶段: ${phaseCode}`)
      
      const newSchedule = {
        id: generateGUID(),
        project_id: currentProjectId,
        phase_cycle: getPhaseCycle(weight.phase_code),
        phase_code: weight.phase_code,
        phase_desc: weight.phase_desc,
        planned_start: null,
        planned_end: null,
        actual_start: null,
        actual_end: null,
        weight: parseInt(weight.weight) || 0,
        completion_rate: 0,
        remark: '',
        progress: JSON.stringify({}) // 初始化空的进度数据
      }

      // 创建到数据库
      await createProjectSchedule(newSchedule)
      planData.push(newSchedule)
      hasChanges = true
    }
  }
  
  if (hasChanges) {
    // 更新前端数据
    periodicPlanList.value = planData.map(schedule => {
      // 初始化进度数据
      const progress = {}
      timePeriods.value.forEach(date => {
        // 如果数据库中有进度数据，使用数据库中的数据，否则默认为0
        const dbProgress = schedule.progress && schedule.progress[date]
        const completionRate = dbProgress ? (parseInt(dbProgress.completion_rate) || 0) : 0
        const weight = parseInt(schedule.weight) || 0
        
        progress[date] = {
          completion_rate: completionRate,
          completed_weight: ((weight * completionRate) / 100).toFixed(1)
        }
      })
      
      return {
        ...schedule,
        progress: progress
      }
    })
    
    console.log('更新后的周期计划数据:', periodicPlanList.value)
    ElMessage.success(`周期计划更新完成，共处理${planData.length}个阶段`)
  } else {
    console.log('周期计划无需更新')
    // 即使没有变化，也要确保前端数据正确显示
    if (periodicPlanList.value.length === 0 && planData.length > 0) {
      periodicPlanList.value = planData.map(schedule => {
        const progress = {}
        timePeriods.value.forEach(date => {
          // 如果数据库中有进度数据，使用数据库中的数据，否则默认为0
          const dbProgress = schedule.progress && schedule.progress[date]
          const completionRate = dbProgress ? (parseInt(dbProgress.completion_rate) || 0) : 0
          const weight = parseInt(schedule.weight) || 0
          
          progress[date] = {
            completion_rate: completionRate,
            completed_weight: ((weight * completionRate) / 100).toFixed(1)
          }
        })
        
        return {
          ...schedule,
          progress: progress
        }
      })
    }
  }
}

// 自动生成周期计划
async function generatePeriodicPlan() {
  generatingPlan.value = true
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) {
      ElMessage.warning('请先选择项目')
      return
    }

    console.log('开始生成周期计划，项目ID:', currentProjectId)

    // 检查权重数据状态
    const weightStatus = await checkWeightDataStatus()
    if (!weightStatus.hasData) {
      ElMessage.warning(weightStatus.message)
      return
    }

    if (weightStatus.message !== '权重配置正确') {
      ElMessage.warning(weightStatus.message)
    }

    // 获取权重设置数据
    const weightData = await getProjectPhaseWeightListByProjectId(currentProjectId)
    let weights = []
    if (Array.isArray(weightData)) {
      weights = weightData
    } else if (weightData && Array.isArray(weightData.data)) {
      weights = weightData.data
    } else if (weightData && Array.isArray(weightData.records)) {
      weights = weightData.records
    } else {
      console.error('权重数据格式不正确:', weightData)
      ElMessage.warning('权重数据格式不正确，请检查权重设置')
      return
    }
    
    if (weights.length === 0) {
      ElMessage.warning('请先在权重设置页面配置项目权重')
      return
    }

    // 调用检查和更新函数
    await checkAndUpdatePeriodicPlan(weights)
    
  } catch (error) {
    console.error('生成周期计划失败:', error)
    ElMessage.error(`生成周期计划失败: ${error.message || '未知错误'}`)
  } finally {
    generatingPlan.value = false
  }
}

// 动态生成时间周期
async function generateTimePeriods() {
  // 如果已经有时间周期，则保留现有数据并添加新的周期
  const existingPeriods = [...timePeriods.value]
  const periods = [...existingPeriods]
  
  // 确定起始日期
  let startDate
  if (existingPeriods.length > 0) {
    // 如果有现有周期，从最后一个周期开始计算
    const lastPeriod = existingPeriods[existingPeriods.length - 1]
    startDate = new Date(
      parseInt(lastPeriod.substring(0, 4)),
      parseInt(lastPeriod.substring(4, 6)) - 1,
      parseInt(lastPeriod.substring(6, 8))
    )
    startDate.setDate(startDate.getDate() + 14) // 从最后一个周期后两周开始
  } else {
    // 如果没有现有周期，从当前日期开始
    const currentDate = new Date()
    const currentFriday = new Date(currentDate)
    const daysToFriday = (5 - currentFriday.getDay() + 7) % 7
    currentFriday.setDate(currentFriday.getDate() + daysToFriday)
    startDate = currentFriday
  }
  
  // 添加新的周期（最多添加4个新周期，避免无限增长）
  const maxNewPeriods = 4
  let addedCount = 0
  
  for (let i = 0; i < maxNewPeriods; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + (i * 14)) // 每两周一个周期
    
    // 检查是否已经超过当前日期太多（比如未来3个月）
    const currentDate = new Date()
    const maxFutureDate = new Date()
    maxFutureDate.setMonth(maxFutureDate.getMonth() + 3)
    
    if (date > maxFutureDate) {
      break
    }
    
    const dateStr = date.getFullYear().toString() + 
                   (date.getMonth() + 1).toString().padStart(2, '0') + 
                   date.getDate().toString().padStart(2, '0')
    
    // 检查是否已存在该周期
    if (!periods.includes(dateStr)) {
      periods.push(dateStr)
      addedCount++
    }
  }
  
  // 如果添加了新的周期，更新timePeriods
  if (addedCount > 0) {
    timePeriods.value = periods
    console.log(`添加了 ${addedCount} 个新周期:`, periods.slice(existingPeriods.length))
    
    // 同步新添加的周期数据
    await syncNewPeriodsData(periods.slice(existingPeriods.length))
  }
  
  console.log('当前所有时间周期:', periods)
}

// 初始化时间周期（保留历史数据）
async function initializeTimePeriods() {
  // 如果已经有时间周期，不要重新生成
  if (timePeriods.value.length > 0) {
    console.log('时间周期已存在，保留现有数据')
    return
  }
  
  // 首次生成时间周期
  const periods = []
  const currentDate = new Date()
  
  // 找到当前周的周五
  const currentFriday = new Date(currentDate)
  const daysToFriday = (5 - currentFriday.getDay() + 7) % 7
  currentFriday.setDate(currentFriday.getDate() + daysToFriday)
  
  // 生成时间周期：前两周 + 当前周 + 未来10周
  for (let i = -2; i < 11; i++) {
    const date = new Date(currentFriday)
    date.setDate(currentFriday.getDate() + (i * 14)) // 每两周一个周期
    const dateStr = date.getFullYear().toString() + 
                   (date.getMonth() + 1).toString().padStart(2, '0') + 
                   date.getDate().toString().padStart(2, '0')
    periods.push(dateStr)
  }
  
  timePeriods.value = periods
  console.log('初始化时间周期（前两周+当前+未来10周）:', periods)
  
  // 同步历史进度数据到新的时间周期
  await syncHistoricalProgressData(periods)
}

// 同步历史进度数据到新的时间周期
async function syncHistoricalProgressData(newPeriods) {
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) {
      console.log('没有项目ID，跳过历史数据同步')
      return
    }
    
    console.log('开始同步历史进度数据...')
    
    // 获取项目阶段数据
    const res = await getProjectScheduleListByProjectId(currentProjectId)
    const allSchedule = Array.isArray(res) ? res : []
    const projectSchedules = allSchedule.filter(item => item.project_id === currentProjectId)
    
    if (projectSchedules.length === 0) {
      console.log('没有找到项目阶段数据，跳过同步')
      return
    }
    
    console.log('开始处理项目阶段数据，优先保留原有结构...')
    
    // 遍历每个项目阶段，优先保留原有数据结构
    for (const schedule of projectSchedules) {
      try {
        // 解析现有的进度数据，优先保留原有结构
        let existingProgress = {}
        if (schedule.progress) {
          if (typeof schedule.progress === 'string') {
            existingProgress = JSON.parse(schedule.progress)
          } else if (typeof schedule.progress === 'object') {
            existingProgress = schedule.progress
          }
        }
        
        console.log(`阶段 ${schedule.phase_code} 原有进度数据结构:`, existingProgress)
        
        // 创建新的进度数据对象，优先保留原有数据
        const updatedProgress = { ...existingProgress }
        let hasChanges = false
        
        // 为新周期添加默认数据，但不覆盖原有数据
        newPeriods.forEach(date => {
          if (!updatedProgress[date]) {
            // 新周期初始化为0
            updatedProgress[date] = {
              completion_rate: 0,
              completed_weight: 0.0
            }
            hasChanges = true
            console.log(`为阶段 ${schedule.phase_code} 添加新周期 ${date} 的默认数据`)
          } else {
            console.log(`阶段 ${schedule.phase_code} 在周期 ${date} 已有数据，保留:`, updatedProgress[date])
          }
        })
        
        // 只有当有新数据添加时才更新数据库
        if (hasChanges) {
          console.log(`更新阶段 ${schedule.phase_code} 的进度数据`)
          
          const updateData = {
            id: schedule.id,
            project_id: schedule.project_id,
            phase_code: schedule.phase_code,
            phase_desc: schedule.phase_desc,
            planned_start: schedule.planned_start,
            planned_end: schedule.planned_end,
            actual_start: schedule.actual_start,
            actual_end: schedule.actual_end,
            weight: schedule.weight,
            completion_rate: schedule.completion_rate,
            remark: schedule.remark,
            progress: JSON.stringify(updatedProgress)
          }
          
          await updateProjectSchedule(schedule.id, updateData)
          console.log(`阶段 ${schedule.phase_code} 进度数据更新完成`)
        } else {
          console.log(`阶段 ${schedule.phase_code} 无需更新，所有周期数据已存在`)
        }
      } catch (error) {
        console.error(`处理阶段 ${schedule.phase_code} 的进度数据失败:`, error)
      }
    }
    
    console.log('历史进度数据同步完成，优先保留了原有数据结构')
  } catch (error) {
    console.error('同步历史进度数据失败:', error)
  }
}

// 同步新添加的周期数据
async function syncNewPeriodsData(newPeriods) {
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) {
      console.log('没有项目ID，跳过新周期数据同步')
      return
    }
    
    console.log('开始同步新周期数据，优先保留原有数据...')
    
    // 获取项目阶段数据
    const res = await getProjectScheduleListByProjectId(currentProjectId)
    const allSchedule = Array.isArray(res) ? res : []
    const projectSchedules = allSchedule.filter(item => item.project_id === currentProjectId)
    
    if (projectSchedules.length === 0) {
      console.log('没有找到项目阶段数据，跳过同步')
      return
    }
    
    // 遍历每个项目阶段，为新周期添加默认进度数据
    for (const schedule of projectSchedules) {
      try {
        // 解析现有的进度数据，优先保留原有结构
        let existingProgress = {}
        if (schedule.progress) {
          if (typeof schedule.progress === 'string') {
            existingProgress = JSON.parse(schedule.progress)
          } else if (typeof schedule.progress === 'object') {
            existingProgress = schedule.progress
          }
        }
        
        console.log(`阶段 ${schedule.phase_code} 原有进度数据结构:`, existingProgress)
        
        // 检查是否需要添加新周期数据
        let needsUpdate = false
        const updatedProgress = { ...existingProgress }
        
        newPeriods.forEach(date => {
          if (!updatedProgress[date]) {
            // 新周期初始化为0
            updatedProgress[date] = {
              completion_rate: 0,
              completed_weight: 0.0
            }
            needsUpdate = true
            console.log(`为阶段 ${schedule.phase_code} 添加新周期 ${date} 的默认数据`)
          } else {
            console.log(`阶段 ${schedule.phase_code} 在周期 ${date} 已有数据，保留:`, updatedProgress[date])
          }
        })
        
        // 只有当有新数据添加时才更新数据库
        if (needsUpdate) {
          console.log(`为阶段 ${schedule.phase_code} 添加新周期数据`)
          
          const updateData = {
            id: schedule.id,
            project_id: schedule.project_id,
            phase_code: schedule.phase_code,
            phase_desc: schedule.phase_desc,
            planned_start: schedule.planned_start,
            planned_end: schedule.planned_end,
            actual_start: schedule.actual_start,
            actual_end: schedule.actual_end,
            weight: schedule.weight,
            completion_rate: schedule.completion_rate,
            remark: schedule.remark,
            progress: JSON.stringify(updatedProgress)
          }
          
          await updateProjectSchedule(schedule.id, updateData)
          console.log(`阶段 ${schedule.phase_code} 新周期数据同步完成`)
        } else {
          console.log(`阶段 ${schedule.phase_code} 无需更新，所有新周期数据已存在`)
        }
      } catch (error) {
        console.error(`处理阶段 ${schedule.phase_code} 的新周期数据失败:`, error)
      }
    }
    
    console.log('新周期数据同步完成，优先保留了原有数据结构')
  } catch (error) {
    console.error('同步新周期数据失败:', error)
  }
}





// 根据阶段编码获取项目周期
function getPhaseCycle(phaseCode) {
  if (phaseCode.startsWith('PL1')) return 'PL1阶段 项目启动'
  if (phaseCode.startsWith('PL2')) return 'PL2阶段 深化设计'
  if (phaseCode.startsWith('PL3')) return 'PL3阶段 设备采购到货'
  if (phaseCode.startsWith('PL4')) return 'PL4阶段 项目实施'
  if (phaseCode.startsWith('PL5')) return 'PL5阶段 项目竣工'
  if (phaseCode.startsWith('PL6')) return 'PL6阶段 项目结束'
  return '其他阶段'
}

// 添加验证完成率的函数
function validateCompletionRate(item, date) {
  const rate = parseInt(item.progress[date].completion_rate) || 0
  if (rate < 0) {
    item.progress[date].completion_rate = 0
    ElMessage.warning('完成率不能小于0%')
  } else if (rate > 100) {
    item.progress[date].completion_rate = 100
    ElMessage.warning('完成率不能大于100%')
  }
  
  // 如果用户降低了进度，检查是否需要重置阶段状态
  if (rate < 100 && item.phaseStatus === 'completed') {
    resetPhaseStatus(item)
  }
}

// 编辑阶段信息
function editPhase(phase) {
  // 检查阶段是否已完成，如果已完成则不允许编辑
  // if (phase.phaseStatus === 'completed') {
  //   ElMessage.warning(`阶段 ${phase.phase_code} 已完成，无法编辑`)
  //   return
  // }
  
  // 将周期计划数据转换为表单数据
  form.value = {
    id: phase.id,
    project_id: phase.project_id,
    phase_code: phase.phase_code,
    phase_desc: phase.phase_desc,
    planned_start: phase.planned_start || '',
    planned_end: phase.planned_end || '',
    actual_start: phase.actual_start || '',
    actual_end: phase.actual_end || '',
    weight: phase.weight,
    completion_rate: phase.completion_rate || 0,
    remark: phase.remark || ''
  }
  dialogVisible.value = true
}

// 修改处理进度变化函数
function handleProgressChange(item, date) {
  // 检查阶段是否已完成
  if (item.phaseStatus === 'completed') {
    ElMessage.warning(`阶段 ${item.phase_code} 已完成，如需修改进度请先降低其他周期的完成率`)
    return
  }
  
  const completionRate = parseInt(item.progress[date].completion_rate) || 0
  const weight = parseInt(item.weight) || 0
  
  // 更新完成权重
  item.progress[date].completed_weight = ((weight * completionRate) / 100).toFixed(1)
  
  // 验证完成率范围
  validateCompletionRate(item, date)
  
  // 检查是否达到100%完成
  if (completionRate === 100) {
    // 将该阶段标记为已完成
    item.phaseStatus = 'completed'
    item.phaseStatusText = '该阶段已完成'
    
    // 其他周期设置为100%
    timePeriods.value.forEach(periodDate => {
      if (periodDate !== date && item.progress[periodDate]) {
        item.progress[periodDate].completion_rate = 100
        item.progress[periodDate].completed_weight = parseFloat(item.progress[periodDate].completed_weight)
      }
    })
    
    ElMessage.success(`阶段 ${item.phase_code} 已完成！`)
  }
  
  // 自动保存进度
  saveProgressToBackend(item, date)
  
  console.log(`阶段 ${item.phase_code} 在 ${formatDate(date)} 的进度更新:`, {
    completionRate: completionRate,
    weight: weight,
    completedWeight: item.progress[date].completed_weight,
    phaseStatus: item.phaseStatus
  })
}

// 保存进度到后端
async function saveProgressToBackend(item, date) {
  try {
    // // 检查阶段是否已完成，如果已完成则不允许保存
    // if (item.phaseStatus === 'completed') {
    //   ElMessage.warning(`阶段 ${item.phase_code} 已完成，无法修改进度`)
    //   return
    // }
    
    // 确保progress是字符串格式
    const progressString = typeof item.progress === 'string' ? item.progress : JSON.stringify(item.progress)
    
    // 更新项目阶段数据，包含进度信息
    const updateData = {
      id: item.id,
      project_id: item.project_id,
      phase_code: item.phase_code,
      phase_desc: item.phase_desc,
      planned_start: item.planned_start,
      planned_end: item.planned_end,
      actual_start: item.actual_start,
      actual_end: item.actual_end,
      weight: item.weight,
      completion_rate: item.completion_rate,
      remark: item.remark,
      progress: progressString // 确保是字符串
    }
    
    console.log('保存进度到数据库:', {
      phase_id: item.id,
      date: date,
      completion_rate: item.progress[date].completion_rate,
      completed_weight: item.progress[date].completed_weight,
      progress_string: progressString
    })
    
    // 调用API更新数据
    await updateProjectSchedule(item.id, updateData)
    
    console.log('进度保存成功')
  } catch (error) {
    console.error('保存进度失败:', error)
    ElMessage.error('保存进度失败，请重试')
  }
}

// 保存所有进度
async function saveAllProgress() {
  savingProgress.value = true
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) {
      ElMessage.warning('请先选择项目')
      return
    }

    // 检查是否有已完成的阶段，如果有则不允许保存
    // const completedPhases = periodicPlanList.value.filter(item => item.phaseStatus === 'completed')
    // if (completedPhases.length > 0) {
    //   const phaseCodes = completedPhases.map(item => item.phase_code).join('、')
    //   ElMessage.warning(`以下阶段已完成，无法修改进度：${phaseCodes}`)
    //   return
    // }

    // 逐条保存，确保progress字段正确格式化
    for (const item of periodicPlanList.value) {
      const progressString = typeof item.progress === 'string' ? item.progress : JSON.stringify(item.progress)
      
      const updateData = {
        id: item.id,
        project_id: item.project_id,
        phase_code: item.phase_code,
        phase_desc: item.phase_desc,
        planned_start: item.planned_start,
        planned_end: item.planned_end,
        actual_start: item.actual_start,
        actual_end: item.actual_end,
        weight: item.weight,
        completion_rate: item.completion_rate,
        remark: item.remark,
        progress: progressString
      }
      
      await updateProjectSchedule(item.id, updateData)
    }
    ElMessage.success('所有进度已保存')
  } catch (error) {
    ElMessage.error('保存所有进度失败')
    console.error('保存所有进度失败:', error)
  } finally {
    savingProgress.value = false
  }
}

// 在权重数据加载完成后同步旧数据
async function syncHistoricalDataAfterWeights() {
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) {
      console.log('没有项目ID，跳过历史数据同步')
      return
    }
    
    console.log('开始同步历史数据到新的时间周期...')
    
    // 使用已有的项目阶段数据，避免重复调用接口
    if (projectScheduleList.value.length === 0) {
      console.log('没有项目阶段数据，跳过同步')
      return
    }
    
    const projectSchedules = projectScheduleList.value
    
    // 遍历每个项目阶段，同步历史进度数据
    for (const schedule of projectSchedules) {
      try {
        // 解析现有的进度数据
        let existingProgress = {}
        if (schedule.progress) {
          if (typeof schedule.progress === 'string') {
            existingProgress = JSON.parse(schedule.progress)
          } else if (typeof schedule.progress === 'object') {
            existingProgress = schedule.progress
          }
        }
        
        // 优化：只处理有实际进度的数据，0值跳过处理
        const effectiveProgress = Object.keys(existingProgress).filter(date => {
          const progress = existingProgress[date]
          return parseInt(progress.completion_rate) > 0 || parseFloat(progress.completed_weight) > 0
        })
        
        if (effectiveProgress.length > 0) {
          console.log(`阶段 ${schedule.phase_code} 有效进度数据:`, effectiveProgress.map(date => ({
            date,
            completion_rate: existingProgress[date].completion_rate,
            completed_weight: existingProgress[date].completed_weight
          })))
        } else {
          console.log(`阶段 ${schedule.phase_code} 无有效进度数据，跳过处理`)
          continue // 跳过无有效数据的阶段
        }
        
        // 优化：快速检查哪些周期缺失数据
        const missingPeriods = []
        timePeriods.value.forEach(date => {
          if (!existingProgress[date]) {
            missingPeriods.push(date)
          }
        })
        
        // 如果有缺失的周期，快速添加默认数据
        if (missingPeriods.length > 0) {
          console.log(`阶段 ${schedule.phase_code} 缺失 ${missingPeriods.length} 个周期数据`)
          
          // 创建新的进度数据，完全保留原有数据，只添加缺失的周期
          const updatedProgress = { ...existingProgress }
          missingPeriods.forEach(date => {
            updatedProgress[date] = {
              completion_rate: 0,
              completed_weight: 0.0
            }
          })
          
          // 批量更新数据库
          const updateData = {
            id: schedule.id,
            project_id: schedule.project_id,
            phase_code: schedule.phase_code,
            phase_desc: schedule.phase_desc,
            planned_start: schedule.planned_start,
            planned_end: schedule.planned_end,
            actual_start: schedule.actual_start,
            actual_end: schedule.actual_end,
            weight: schedule.weight,
            completion_rate: schedule.completion_rate,
            remark: schedule.remark,
            progress: JSON.stringify(updatedProgress)
          }
          
          await updateProjectSchedule(schedule.id, updateData)
          console.log(`阶段 ${schedule.phase_code} 周期数据同步完成`)
        } else {
          console.log(`阶段 ${schedule.phase_code} 所有周期数据完整，无需同步`)
        }
      } catch (error) {
        console.error(`同步阶段 ${schedule.phase_code} 的历史数据失败:`, error)
      }
    }
    
    // 同步完成后，直接更新前端数据，避免重新调用接口
    console.log('历史数据同步完成，更新前端显示数据...')
    
    // 直接使用已有的数据，避免重复调用接口
    const latestProjectSchedules = projectScheduleList.value
    
          // 重新转换数据格式，确保历史数据正确显示
      periodicPlanList.value = latestProjectSchedules.map(schedule => {
        // 解析数据库中的进度数据
        let dbProgress = {}
        if (schedule.progress) {
          try {
            if (typeof schedule.progress === 'string') {
              dbProgress = JSON.parse(schedule.progress)
            } else if (typeof schedule.progress === 'object') {
              dbProgress = schedule.progress
            }
          } catch (error) {
            console.error('解析进度数据失败:', error)
            dbProgress = {}
          }
        }
        
        // 智能进度数据处理：实现阶段完成逻辑和两周限制
        const currentDate = new Date()
        const currentWeekStart = new Date(currentDate)
        currentWeekStart.setDate(currentDate.getDate() - currentDate.getDay()) // 当前周开始
        
        // 计算当前周的前两周范围
        const twoWeeksAgo = new Date(currentWeekStart)
        twoWeeksAgo.setDate(currentWeekStart.getDate() - 14)
        
        // 过滤出两周内的有效进度数据
        const effectiveDbData = Object.keys(dbProgress).filter(date => {
          const dateProgress = dbProgress[date]
          const hasProgress = parseInt(dateProgress.completion_rate) > 0 || parseFloat(dateProgress.completed_weight) > 0
          
          // 只处理两周内的数据
          const dateObj = new Date(
            parseInt(date.substring(0, 4)),
            parseInt(date.substring(4, 6)) - 1,
            parseInt(date.substring(6, 8))
          )
          const isWithinTwoWeeks = dateObj >= twoWeeksAgo
          
          return hasProgress && isWithinTwoWeeks
        })
        
        // 检查是否有100%完成的周期
        const hasCompletedPhase = effectiveDbData.some(date => {
          const dateProgress = dbProgress[date]
          return parseInt(dateProgress.completion_rate) === 100
        })
        
        // 获取两周前的最高完成率
        const historicalData = Object.keys(dbProgress).filter(date => {
          const dateObj = new Date(
            parseInt(date.substring(0, 4)),
            parseInt(date.substring(4, 6)) - 1,
            parseInt(date.substring(6, 8))
          )
          return dateObj < twoWeeksAgo
        })
        
        let maxHistoricalProgress = 0
        if (historicalData.length > 0) {
          historicalData.forEach(date => {
            const dateProgress = dbProgress[date]
            const progressRate = parseInt(dateProgress.completion_rate) || 0
            if (progressRate > maxHistoricalProgress) {
              maxHistoricalProgress = progressRate
            }
          })
        }
        
        // 初始化进度数据
        const progress = {}
        
        // 只复制两周内的有效进度数据
        effectiveDbData.forEach(date => {
          const dateProgress = dbProgress[date]
          progress[date] = {
            completion_rate: parseInt(dateProgress.completion_rate) || 0,
            completed_weight: parseFloat(dateProgress.completed_weight) || 0.0
          }
        })
        
        // 如果有100%完成的周期，其他周期设置为100%
        if (hasCompletedPhase) {
          timePeriods.value.forEach(date => {
            if (!progress[date]) {
              progress[date] = {
                completion_rate: 100,
                completed_weight: parseFloat(schedule.weight) || 0.0
              }
            }
          })
        } else {
          // 为所有时间周期设置默认值，前第二周使用历史最高进度
          timePeriods.value.forEach((date, index) => {
            if (!progress[date]) {
              if (index === 1 && maxHistoricalProgress > 0) {
                // 前第二周使用历史最高进度
                progress[date] = {
                  completion_rate: maxHistoricalProgress,
                  completed_weight: ((parseFloat(schedule.weight) || 0) * maxHistoricalProgress / 100).toFixed(1)
                }
              } else {
                progress[date] = {
                  completion_rate: 0,
                  completed_weight: 0.0
                }
              }
            }
          })
        }
        
        // 只显示有实际进度的数据
        if (effectiveDbData.length > 0) {
          console.log(`阶段 ${schedule.phase_code} 有效进度数据:`, effectiveDbData.map(date => ({
            date,
            completion_rate: progress[date].completion_rate,
            completed_weight: progress[date].completed_weight
          })))
        }
        
        // 添加阶段完成状态信息
        const result = {
          ...schedule,
          progress: progress,
          phaseStatus: hasCompletedPhase ? 'completed' : 'in_progress',
          phaseStatusText: hasCompletedPhase ? '该阶段已完成' : '进行中',
          maxHistoricalProgress: maxHistoricalProgress,
          isWithinTwoWeeks: true
        }
        
        return result
      })
    
          console.log('前端数据更新完成，历史数据同步流程结束')
      
          // 数据同步完成后，执行权重和完成率同步
    syncWeightAndCompletionRate()
    
    // 刷新统计信息显示
    refreshStatsAfterUpdate()
  } catch (error) {
    console.error('同步历史数据失败:', error)
  }
}

// 实时同步权重和完成率
function syncWeightAndCompletionRate() {
  try {
    console.log('开始实时同步权重和完成率...')
    
    // 遍历所有周期计划，确保权重和完成率数据一致
    periodicPlanList.value.forEach(item => {
      const weight = parseInt(item.weight) || 0
      
      // 遍历所有时间周期
      timePeriods.value.forEach(date => {
        if (item.progress[date]) {
          const completionRate = parseInt(item.progress[date].completion_rate) || 0
          const calculatedWeight = ((weight * completionRate) / 100).toFixed(1)
          
          // 如果计算出的权重与存储的权重不一致，更新权重
          if (parseFloat(calculatedWeight) !== parseFloat(item.progress[date].completed_weight)) {
            item.progress[date].completed_weight = parseFloat(calculatedWeight)
            console.log(`阶段 ${item.phase_code} 在周期 ${date} 同步权重: ${item.progress[date].completed_weight}`)
          }
        }
      })
      
      // 检查阶段完成状态
      checkAndUpdatePhaseStatus(item)
    })
    
    console.log('权重和完成率同步完成')
  } catch (error) {
    console.error('同步权重和完成率失败:', error)
  }
}

// 检查并更新阶段完成状态
function checkAndUpdatePhaseStatus(item) {
  // 检查是否有100%完成的周期
  const hasCompletedPeriod = timePeriods.value.some(date => {
    return item.progress[date] && parseInt(item.progress[date].completion_rate) === 100
  })
  
  if (hasCompletedPeriod && item.phaseStatus !== 'completed') {
    // 更新为已完成状态
    item.phaseStatus = 'completed'
    item.phaseStatusText = '该阶段已完成'
    console.log(`阶段 ${item.phase_code} 状态更新为已完成`)
  } else if (!hasCompletedPeriod && item.phaseStatus === 'completed') {
    // 更新为进行中状态
    item.phaseStatus = 'in_progress'
    item.phaseStatusText = '进行中'
    console.log(`阶段 ${item.phase_code} 状态更新为进行中`)
  }
}

// 重置阶段完成状态（当用户降低进度时调用）
function resetPhaseStatus(item) {
  if (item.phaseStatus === 'completed') {
    item.phaseStatus = 'in_progress'
    item.phaseStatusText = '进行中'
    console.log(`阶段 ${item.phase_code} 状态已重置为进行中`)
  }
}










// 监听权重变化，自动同步完成率
watch(() => weightList.value, (newWeights, oldWeights) => {
  if (newWeights.length > 0 && oldWeights && oldWeights.length > 0) {
    // 检查权重值是否有变化
    let hasWeightChange = false
    for (let i = 0; i < newWeights.length; i++) {
      const newWeight = parseInt(newWeights[i].weight) || 0
      const oldWeight = parseInt(oldWeights[i].weight) || 0
      if (newWeight !== oldWeight) {
        hasWeightChange = true
        console.log(`权重变化检测: ${newWeights[i].phase_code} ${oldWeight}% -> ${newWeight}%`)
        break
      }
    }
    
    if (hasWeightChange) {
      console.log('检测到权重值变化，更新周期计划中的权重')
      // 更新周期计划中的权重值
      periodicPlanList.value.forEach(item => {
        const weightData = newWeights.find(w => w.phase_code === item.phase_code)
        if (weightData) {
          const newWeight = parseInt(weightData.weight) || 0
          if (parseInt(item.weight) !== newWeight) {
            item.weight = newWeight
            console.log(`更新阶段 ${item.phase_code} 权重: ${item.weight} -> ${newWeight}`)
            
            // 重新计算所有周期的完成权重
            timePeriods.value.forEach(date => {
              if (item.progress[date]) {
                const completionRate = parseInt(item.progress[date].completion_rate) || 0
                item.progress[date].completed_weight = ((newWeight * completionRate) / 100).toFixed(1)
              }
            })
          }
        }
      })
      
      // 自动保存更新后的数据
      saveAllProgress()
    }
  }
}, { deep: true })

// 生成32位GUID
function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  }).replace(/-/g, '')
}

// 打开对话框
function openDialog(schedule = null) {
  if (schedule) {
    form.value = { ...schedule }
  } else {
    form.value = {
      id: null,
      project_id: props.projectData.project_id || props.projectId || '',
      phase_code: '',
      phase_desc: '',
      planned_start: '',
      planned_end: '',
      actual_start: '',
      actual_end: '',
      weight: 0,
      completion_rate: 0,
      remark: ''
    }
  }
  dialogVisible.value = true
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate(async (valid) => {
      if (!valid) return
      
      submitLoading.value = true
      
      if (!form.value.id) {
        const payload = { ...form.value }
        payload.id = generateGUID()
        // 初始化空的进度数据
        payload.progress = JSON.stringify({})
        console.log('创建项目阶段，payload:', payload)
        await createProjectSchedule(payload)
        ElMessage.success('项目阶段添加成功')
      } else {
        // 确保progress字段是字符串格式
        const updatePayload = { ...form.value }
        if (updatePayload.progress && typeof updatePayload.progress !== 'string') {
          updatePayload.progress = JSON.stringify(updatePayload.progress)
        }
        console.log('更新项目阶段，payload:', updatePayload)
        await updateProjectSchedule(form.value.id, updatePayload)
        ElMessage.success('项目阶段更新成功')
      }
      
      dialogVisible.value = false
      loadProjectSchedule()
    })
  } catch (error) {
    ElMessage.error('操作失败，请重试')
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 删除项目阶段
function handleDelete(id) {
  ElMessageBox.confirm('确认删除该项目阶段？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProjectSchedule(id)
      ElMessage.success('删除成功')
      loadProjectSchedule()
    } catch (error) {
      ElMessage.error('删除失败，请重试')
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

// 刷新时间周期
function refreshTimePeriods() {
  try {
    // 保存现有的进度数据
    const existingProgress = {}
    periodicPlanList.value.forEach(plan => {
      existingProgress[plan.phase_code] = plan.progress
    })
    
    // 重新生成时间周期
    generateTimePeriods()
    
    // 恢复进度数据，并为新的时间周期初始化默认值
    periodicPlanList.value.forEach(plan => {
      const savedProgress = existingProgress[plan.phase_code] || {}
      const newProgress = {}
      
      timePeriods.value.forEach(date => {
        // 如果之前有这个日期的进度数据，保留；否则初始化为0
        if (savedProgress[date]) {
          newProgress[date] = savedProgress[date]
        } else {
          newProgress[date] = {
            completion_rate: 0,
            completed_weight: 0.0
          }
        }
      })
      
      plan.progress = newProgress
    })
    
    ElMessage.success('时间周期刷新成功')
    console.log('时间周期已刷新，当前周期数量:', timePeriods.value.length)
  } catch (error) {
    console.error('刷新时间周期失败:', error)
    ElMessage.error('刷新时间周期失败')
  }
}

// 刷新数据
function refreshData() {
  loadProjectSchedule()
  ElMessage.success('数据刷新成功')
}




// 加载项目阶段列表
async function loadProjectSchedule() {
  loading.value = true
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    
    if (currentProjectId) {
      console.log('加载项目阶段，项目ID:', currentProjectId)
      
      const res = await getProjectScheduleListByProjectId(currentProjectId)
      const allSchedule = Array.isArray(res) ? res : []
      
      // 过滤当前项目的数据
      projectScheduleList.value = allSchedule.filter(item => item.project_id === currentProjectId)
      
      // 确保时间周期已生成
      if (timePeriods.value.length === 0) {
        await initializeTimePeriods()
      } else {
        // 如果已有时间周期，检查是否需要添加新的周期
        await generateTimePeriods()
      }
      
      // 将项目阶段数据转换为周期计划格式，并自动同步缺失的周期数据
      periodicPlanList.value = projectScheduleList.value.map(schedule => {
        // 解析数据库中的进度数据
        let dbProgress = {}
        if (schedule.progress) {
          try {
            // 如果progress是字符串，尝试解析为JSON
            if (typeof schedule.progress === 'string') {
              dbProgress = JSON.parse(schedule.progress)
            } else if (typeof schedule.progress === 'object') {
              dbProgress = schedule.progress
            }
            console.log(`阶段 ${schedule.phase_code} 数据库原始进度数据:`, schedule.progress)
            console.log(`阶段 ${schedule.phase_code} 解析后的进度数据:`, dbProgress)
          } catch (error) {
            console.error('解析进度数据失败:', error)
            dbProgress = {}
          }
        }
        
        // 优化：先处理已存在的完成率和权重数据，其他周期默认处理
        const progress = {}
        let hasMissingData = false
        
        // 优化：只处理有实际进度的数据，0值直接使用默认数据
        const effectiveDbData = Object.keys(dbProgress).filter(date => {
          const dateProgress = dbProgress[date]
          return parseInt(dateProgress.completion_rate) > 0 || parseFloat(dateProgress.completed_weight) > 0
        })
        
        // 第一步：只复制有实际进度的数据库数据
        effectiveDbData.forEach(date => {
          const dateProgress = dbProgress[date]
          progress[date] = {
            completion_rate: parseInt(dateProgress.completion_rate) || 0,
            completed_weight: parseFloat(dateProgress.completed_weight) || 0.0
          }
        })
        
        // 第二步：为所有时间周期设置默认值（包括0值的数据库数据）
        timePeriods.value.forEach(date => {
          if (!progress[date]) {
            progress[date] = {
              completion_rate: 0,
              completed_weight: 0.0
            }
            hasMissingData = true
          }
        })
        
        // 只显示有实际进度的数据
        if (effectiveDbData.length > 0) {
          console.log(`阶段 ${schedule.phase_code} 有效进度数据:`, effectiveDbData.map(date => ({
            date,
            completion_rate: progress[date].completion_rate,
            completed_weight: progress[date].completed_weight
          })))
        } else {
          console.log(`阶段 ${schedule.phase_code} 无有效进度数据，使用默认值`)
        }
        
        // 如果有缺失的周期数据，标记需要同步
        if (hasMissingData) {
          console.log(`阶段 ${schedule.phase_code} 检测到新周期数据，将在后续自动同步到数据库`)
        }
        
        return {
          ...schedule,
          progress: progress
        }
      })
      
      console.log('转换后的周期计划数据:', periodicPlanList.value)
      
      // 数据转换完成后，执行权重和完成率同步
      syncWeightAndCompletionRate()
      
      currentPage.value = 1
      console.log('当前项目阶段数量:', projectScheduleList.value.length)
      console.log('周期计划数量:', periodicPlanList.value.length)
      
      // 检查是否有权重数据
      try {
        const weightStatus = await checkWeightDataStatus()
        weightStatusMessage.value = weightStatus.message
        weightStatusType.value = weightStatus.hasData ? 'success' : 'warning'
        
        if (weightStatus.hasData) {
          const weightData = await getProjectPhaseWeightListByProjectId(currentProjectId)
          let weights = []
          if (Array.isArray(weightData)) {
            weights = weightData
          } else if (weightData && Array.isArray(weightData.data)) {
            weights = weightData.data
          } else if (weightData && Array.isArray(weightData.records)) {
            weights = weightData.records
          }
          
          console.log('项目权重数据已存在，权重数量:', weights.length)
          weightList.value = weights
          
          // 检查是否需要生成或更新周期计划
          // 只有在周期计划为空时才检查更新
          if (periodicPlanList.value.length === 0) {
            console.log('周期计划为空，检查是否需要生成')
            await checkAndUpdatePeriodicPlan(weights)
          } else {
            console.log('周期计划已存在，跳过自动生成')
          }
          
          // 在权重数据加载完成后，进行旧数据同步
          console.log('权重数据加载完成，开始同步旧数据...')
          await syncHistoricalDataAfterWeights()
        }
      } catch (weightError) {
        console.error('检查权重数据失败:', weightError)
        weightStatusMessage.value = '检查权重数据失败，请手动配置权重'
        weightStatusType.value = 'error'
      }
    } else {
      projectScheduleList.value = []
      periodicPlanList.value = []
      console.log('没有项目编号，不加载项目阶段')
    }
  } catch (error) {
    ElMessage.error('加载项目阶段失败')
    console.error('加载项目阶段失败:', error)
    projectScheduleList.value = []
    periodicPlanList.value = []
  } finally {
    loading.value = false
  }
}



// 监听项目数据变化
watch(() => props.projectData, (newProjectData) => {
  if (newProjectData && newProjectData.project_id) {
    if (dialogVisible.value && !form.value.project_id) {
      form.value.project_id = newProjectData.project_id
    }
    loadProjectSchedule()
  }
}, { deep: true })

// 监听周期计划数据变化，自动更新统计信息
watch(() => periodicPlanList.value, (newPlanList) => {
  if (newPlanList && newPlanList.length > 0) {
    // 延迟执行，确保数据完全加载
    setTimeout(() => {
      displayOptimizedStats()
    }, 200)
  }
}, { deep: true })

// 监听项目ID变化
watch(() => props.projectId, (newProjectId) => {
  if (newProjectId) {
    console.log('项目ID变化，重新加载项目阶段:', newProjectId)
    loadProjectSchedule()
  }
})

// 监听权重变化，自动更新周期计划
watch(() => weightList.value, (newWeights, oldWeights) => {
  // 避免在初始化时重复调用
  if (newWeights.length > 0 && (!oldWeights || oldWeights.length === 0)) {
    console.log('权重数据初始化，检查周期计划')
    // 初始化时不立即调用，让loadProjectSchedule处理
    return
  }
  
  if (newWeights.length > 0 && oldWeights && oldWeights.length > 0) {
    console.log('权重数据变化，检查更新周期计划')
    // 只在权重数据真正变化时才检查更新
    checkAndUpdatePeriodicPlan(newWeights)
  }
}, { deep: true })

// 监听权重数据变化，检查权重值是否发生变化
watch(() => weightList.value, (newWeights, oldWeights) => {
  if (newWeights.length > 0 && oldWeights && oldWeights.length > 0) {
    // 检查权重值是否有变化
    let hasWeightChange = false
    for (let i = 0; i < newWeights.length; i++) {
      const newWeight = parseInt(newWeights[i].weight) || 0
      const oldWeight = parseInt(oldWeights[i].weight) || 0
      if (newWeight !== oldWeight) {
        hasWeightChange = true
        console.log(`权重变化检测: ${newWeights[i].phase_code} ${oldWeight}% -> ${newWeight}%`)
        break
      }
    }
    
    if (hasWeightChange) {
      console.log('检测到权重值变化，更新周期计划')
      checkAndUpdatePeriodicPlan(newWeights)
    }
  }
}, { deep: true })

// 添加一个方法来手动同步权重数据
async function syncWeightData() {
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) {
      ElMessage.warning('请先选择项目')
      return
    }

    console.log('手动同步权重数据...')
    
    // 重新获取权重数据
    const weightData = await getProjectPhaseWeightListByProjectId(currentProjectId)
    let weights = []
    if (Array.isArray(weightData)) {
      weights = weightData
    } else if (weightData && Array.isArray(weightData.data)) {
      weights = weightData.data
    } else if (weightData && Array.isArray(weightData.records)) {
      weights = weightData.records
    }
    
    if (weights.length > 0) {
      weightList.value = weights
      // 更新周期计划
      await checkAndUpdatePeriodicPlan(weights)
      ElMessage.success('权重数据同步成功')
    } else {
      ElMessage.warning('未找到权重数据')
    }
  } catch (error) {
    console.error('同步权重数据失败:', error)
    ElMessage.error('同步权重数据失败')
  }
}

// 监听搜索和筛选变化时，重置分页到第一页
watch([searchKeyword, filterStatus], () => {
  currentPage.value = 1
})

// 监听页面可见性变化，当页面重新获得焦点时同步权重数据
onMounted(() => {
  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange)
  
  try {
    loadProjectSchedule()
  } catch (error) {
    console.error('项目阶段页面初始化失败:', error)
  }
})

// 页面可见性变化处理
function handleVisibilityChange() {
  if (!document.hidden) {
    // 页面重新可见时，检查是否需要同步权重数据
    console.log('页面重新可见，检查权重数据同步')
    // 延迟执行，避免频繁调用
    setTimeout(() => {
      syncWeightData()
    }, 1000)
  }
}

// 查看阶段详情
function viewPhaseDetail(phase) {
  selectedPhase.value = phase
  detailDialogVisible.value = true
}

// 从详情页面编辑
function editFromDetail() {
  if (selectedPhase.value) {
    editPhase(selectedPhase.value)
    detailDialogVisible.value = false
  }
}

// 获取进度详情数据
function getProgressDetailData() {
  if (!selectedPhase.value || !selectedPhase.value.progress) {
    return []
  }
  
  return timePeriods.value.map(date => {
    const progress = selectedPhase.value.progress[date] || {}
    return {
      date: date,
      completion_rate: progress.completion_rate || 0,
      completed_weight: progress.completed_weight || '0.0',
      status: getProgressStatusText(progress.completion_rate || 0)
    }
  })
}

// 获取进度状态类型
function getProgressStatusType(completionRate) {
  const rate = parseInt(completionRate) || 0
  if (rate >= 100) return 'success'
  if (rate >= 80) return 'warning'
  if (rate >= 50) return 'primary'
  return 'info'
}

// 获取进度状态文本
function getProgressStatusText(completionRate) {
  const rate = parseInt(completionRate) || 0
  if (rate >= 100) return '已完成'
  if (rate >= 80) return '接近完成'
  if (rate >= 50) return '进行中'
  if (rate > 0) return '已开始'
  return '未开始'
}

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>

<style scoped>
.timeline-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.timeline-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.create-btn {
  padding: 12px 20px;
  font-weight: 500;
  border-radius: 8px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #67c23a;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.schedule-table-section {
  margin-bottom: 30px;
}

.schedule-table-section h3 {
  margin-bottom: 16px;
  color: #303133;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.progress-stats {
  margin-bottom: 30px;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.gantt-section {
  margin-bottom: 30px;
}

.gantt-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.gantt-header h3 {
  margin: 0;
  color: #303133;
}

.gantt-controls {
  display: flex;
  gap: 8px;
}

.gantt-container {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  height: 400px;
  background: #fafafa;
}

.gantt-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.placeholder-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.placeholder-desc {
  font-size: 14px;
  margin-top: 8px;
  text-align: center;
}

/* 周期计划表格样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  width: 100%;
  position: relative;
}

.table-title {
  flex: 0 0 auto;
  min-width: 0;
}

.table-title h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.table-actions {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  gap: 12px;
  z-index: 10;
}

.save-progress-btn {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  margin-right: 20px; /* 右侧间隔 */
  transition: all 0.3s ease;
}

.save-progress-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

.save-progress-btn:active {
  transform: translateY(0);
}

.periodic-table {
  margin-bottom: 20px;
}

/* 响应式表格容器 */
.table-responsive-container {
  overflow-x: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.responsive-table {
  min-width: 800px; /* 确保表格有最小宽度 */
}

/* 响应式进度单元格样式 */
.progress-cell-responsive {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 3px;
  padding: 3px 0;
  min-height: 60px;
}

.completion-input {
  width: 45px !important;
  text-align: center;
}

.completion-input .el-input__inner {
  text-align: center;
  font-size: 11px;
  padding: 2px 4px;
  height: 24px;
  line-height: 24px;
}

.completion-input .el-input__suffix {
  font-size: 9px;
  color: #909399;
}

.completed-weight-responsive {
  font-size: 10px;
  color: #67c23a;
  font-weight: 500;
  line-height: 1;
  text-align: center;
}

.date-header {
  text-align: center;
  font-size: 10px;
  color: #606266;
  padding: 3px 0;
}

.date-label {
  font-weight: 500;
  line-height: 1;
}

/* 简化进度单元格样式（保留向后兼容） */
.progress-cell-simple {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 4px 0;
}

.completed-weight-simple {
  font-size: 11px;
  color: #67c23a;
  font-weight: 500;
  line-height: 1;
}

/* 优化输入框样式 */
.progress-cell-simple .el-input {
  --el-input-border-radius: 4px;
}

.progress-cell-simple .el-input__inner {
  text-align: center;
  font-size: 12px;
  padding: 2px 4px;
}

.progress-cell-simple .el-input__suffix {
  font-size: 10px;
  color: #909399;
}

/* 总计行样式优化 */
.total-row {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-top: none;
  padding: 8px 16px;
  font-weight: 500;
  font-size: 13px;
  min-width: 800px; /* 与表格保持一致 */
  overflow-x: auto;
}

.total-label {
  min-width: 120px;
  max-width: 150px;
  color: #303133;
  flex-shrink: 0;
}

.total-weight {
  min-width: 80px;
  max-width: 100px;
  color: #409eff;
  text-align: center;
  flex-shrink: 0;
}

.total-progress {
  flex: 1;
  text-align: center;
  min-width: 90px;
  max-width: 120px;
  flex-shrink: 0;
}

.total-completion {
  font-size: 11px;
  color: #67c23a;
  margin-bottom: 2px;
}

.total-completed-weight {
  font-size: 9px;
  color: #909399;
}

/* 阶段完成情况统计样式 */
.phase-stats-section {
  margin-top: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 16px;
  border: 1px solid #e9ecef;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.stats-header {
  text-align: center;
  margin-bottom: 32px;
}

.stats-title {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.stats-icon {
  font-size: 28px;
  color: #409eff;
}

.stats-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
  font-weight: 400;
}

.phase-stats-container {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 32px;
  align-items: start;
}

/* 项目总体进度卡片 */
.phase-stats-summary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px;
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.summary-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.summary-icon {
  font-size: 24px;
  color: rgba(255, 255, 255, 0.9);
}

.summary-title {
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.summary-progress {
  text-align: center;
}

.progress-circle {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.progress-value {
  font-size: 32px;
  font-weight: 700;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.progress-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
}

.summary-content {
  margin-top: 20px;
}

.summary-grid {
  display: grid;
  gap: 16px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.item-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 10px;
  color: white;
  font-size: 18px;
}

.item-content {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.item-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 400;
}

.item-value {
  font-size: 16px;
  font-weight: 600;
  color: white;
}

/* 各阶段完成情况表格 */
.phase-stats-details {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  border: 1px solid #f0f0f0;
  position: relative;
  overflow: hidden;
}

.phase-stats-details::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 50%, #e6a23c 100%);
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

.details-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.details-icon {
  font-size: 20px;
  color: #409eff;
}

.details-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.details-count {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
  padding: 8px 16px;
  border-radius: 20px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 阶段统计分页控件样式 */
.phase-stats-pagination {
  display: flex;
  justify-content: center;
  margin: 16px 0;
  padding: 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.phase-stats-pagination .el-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-border-radius: 8px;
}

.phase-stats-pagination .el-pagination .el-pager li {
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.phase-stats-pagination .el-pagination .el-pager li:hover {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.phase-stats-pagination .el-pagination .el-pager li.is-active {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

/* 表格样式 */
.phase-stats-table {
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: white;
}

.table-header {
  display: grid;
  grid-template-columns: 120px 1fr 100px 120px 100px;
  gap: 16px;
  padding: 20px 0px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 2px solid #e9ecef;
  position: relative;
}

.table-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent 0%, #409eff 50%, transparent 100%);
}

.header-cell {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding: 0 8px;
}

.phase-code-header {
  text-align: center;
  width: 120px;
}

.phase-desc-header {
  text-align: left;
  flex: 1;
}

.phase-weight-header {
  text-align: center;
  width: 100px;
}

.phase-completion-header {
  text-align: center;
  width: 120px;
}

.phase-contribution-header {
  text-align: center;
  width: 100px;
}

.table-body {
  max-height: 400px;
  overflow-y: auto;
  background: white;
}

.table-body::-webkit-scrollbar {
  width: 8px;
}

.table-body::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 4px;
}

.table-body::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #c0c4cc 0%, #909399 100%);
  border-radius: 4px;
}

.table-body::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #909399 0%, #606266 100%);
}

.table-row {
  display: grid;
  grid-template-columns: 120px 1fr 100px 120px 100px;
  gap: 16px;
  padding: 20px 0px;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  border-bottom: 1px solid #f5f7fa;
}

.table-row:last-child {
  border-bottom: none;
}

.row-even {
  background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
}

.row-odd {
  background: white;
}

.table-row:hover {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.15);
  border-radius: 8px;
  margin: 0 4px;
  z-index: 1;
}

.table-row:hover::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(180deg, #409eff 0%, #67c23a 100%);
  border-radius: 0 4px 4px 0;
}

.table-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 24px;
  transition: all 0.3s ease;
  padding:0px 10px;
}

.phase-code-cell {
  justify-content: center;
  width: 120px;
}

.phase-desc-cell {
  justify-content: flex-start;
  text-align: left;
  flex: 1;
  min-width: 0;
}

.phase-weight-cell {
  justify-content: center;
  width: 100px;
}

.phase-completion-cell {
  flex-direction: column;
  gap: 8px;
  align-items: center;
  width: 120px;
}

.phase-contribution-cell {
  justify-content: center;
  width: 100px;
}

.phase-desc-text {
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color 0.3s ease;
}

.table-row:hover .phase-desc-text {
  color: #409eff;
}

.weight-badge {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.weight-badge::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s ease;
}

.table-row:hover .weight-badge::before {
  left: 100%;
}

.table-row:hover .weight-badge {
  transform: scale(1.05);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

.completion-text {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  transition: color 0.3s ease;
}

.table-row:hover .completion-text {
  color: #409eff;
}

.contribution-badge {
  background: linear-gradient(135deg, #f56c6c 0%, #e6a23c 100%);
  color: white;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.contribution-badge::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s ease;
}

.table-row:hover .contribution-badge::before {
  left: 100%;
}

.table-row:hover .contribution-badge {
  transform: scale(1.05);
  box-shadow: 0 6px 20px rgba(245, 108, 108, 0.4);
}

.no-data {
  padding: 60px 20px;
  text-align: center;
  background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
}

.no-data .el-empty__description {
  color: #909399;
  font-size: 14px;
}

/* 进度条样式优化 */
.phase-completion-cell .el-progress {
  width: 100%;
  max-width: 80px;
}

.phase-completion-cell .el-progress__bar {
  border-radius: 10px;
  overflow: hidden;
}

.phase-completion-cell .el-progress__inner {
  border-radius: 10px;
  transition: all 0.3s ease;
}

.table-row:hover .phase-completion-cell .el-progress__inner {
  transform: scaleY(1.1);
}

/* 响应式设计优化 */
@media (max-width: 1200px) {
  .phase-stats-container {
    grid-template-columns: 1fr;
    gap: 24px;
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 100px 1fr 70px 100px 80px;
    gap: 12px;
    padding: 16px 12px;
  }
  
  .details-count {
    padding: 6px 12px;
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .phase-stats-section {
    padding: 16px;
  }
  
  .stats-title {
    font-size: 20px;
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 80px 1fr 60px 80px 60px;
    gap: 8px;
    padding: 12px 8px;
  }
  
  .header-cell,
  .table-cell {
    font-size: 12px;
  }
  
  .phase-desc-text {
    max-width: 120px;
    font-size: 11px;
  }
  
  .weight-badge,
  .contribution-badge {
    padding: 4px 10px;
    font-size: 11px;
  }
  
  .details-count {
    padding: 4px 8px;
    font-size: 12px;
  }
}

/* 添加动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.table-row {
  animation: fadeInUp 0.6s ease forwards;
}

.table-row:nth-child(1) { animation-delay: 0.1s; }
.table-row:nth-child(2) { animation-delay: 0.2s; }
.table-row:nth-child(3) { animation-delay: 0.3s; }
.table-row:nth-child(4) { animation-delay: 0.4s; }
.table-row:nth-child(5) { animation-delay: 0.5s; }
.table-row:nth-child(6) { animation-delay: 0.6s; }
.table-row:nth-child(7) { animation-delay: 0.7s; }
.table-row:nth-child(8) { animation-delay: 0.8s; }
.table-row:nth-child(9) { animation-delay: 0.9s; }
.table-row:nth-child(10) { animation-delay: 1.0s; }
.table-row:nth-child(11) { animation-delay: 1.1s; }

/* 添加加载状态样式 */
.table-row.loading {
  opacity: 0.6;
  pointer-events: none;
}

.table-row.loading::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 20px;
  height: 20px;
  margin: -10px 0 0 -10px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 添加选中状态样式 */
.table-row.selected {
  background: linear-gradient(135deg, #e6f7ff 0%, #b3e0ff 100%);
  border: 2px solid #409eff;
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.2);
}

.table-row.selected::before {
  background: linear-gradient(180deg, #409eff 0%, #67c23a 100%);
  width: 6px;
}

/* 添加完成状态的特殊样式 */
.table-row.completed {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-left: 4px solid #67c23a;
}

.table-row.completed .weight-badge {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.table-row.completed .contribution-badge {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

/* 添加警告状态的特殊样式 */
.table-row.warning {
  background: linear-gradient(135deg, #fff7e6 0%, #fef0e6 100%);
  border-left: 4px solid #e6a23c;
}

.table-row.warning .weight-badge {
  background: linear-gradient(135deg, #e6a23c 0%, #f0a020 100%);
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
}

.table-row.warning .contribution-badge {
  background: linear-gradient(135deg, #e6a23c 0%, #f0a020 100%);
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
}

.stats-explanation {
  margin-top: 16px;
}

.explanation-content {
  font-size: 13px;
  line-height: 1.6;
}

.explanation-content p {
  margin: 4px 0;
}

.explanation-content .example {
  margin-top: 8px;
  padding: 8px;
  background: #f0f9ff;
  border-left: 3px solid #409eff;
  border-radius: 4px;
  font-style: italic;
  color: #409eff;
}

.explanation-content .note {
  margin-top: 8px;
  padding: 8px;
  background: #fff7e6;
  border-left: 3px solid #e6a23c;
  border-radius: 4px;
  font-style: italic;
  color: #e6a23c;
  font-size: 12px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  margin: 0;
  padding: 4px 8px;
  font-size: 12px;
}

/* 阶段详情样式 */
.phase-detail {
  padding: 0;
}

.progress-detail h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.progress-detail .el-table {
  margin-top: 8px;
}

/* ===== 响应式设计优化 ===== */

/* 超小屏幕 (手机竖屏) */
@media (max-width: 480px) {
  .timeline-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .header-actions .el-button {
    flex: 1;
    min-width: 120px;
    font-size: 12px;
    padding: 8px 12px;
  }
  
  .page-title {
    font-size: 20px;
    flex-wrap: wrap;
  }
  
  .search-section {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-input {
    max-width: none;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .table-actions {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .table-actions .el-button {
    flex: 1;
    min-width: 140px;
    font-size: 12px;
    padding: 8px 12px;
  }
  
  .responsive-table {
    min-width: 600px;
    font-size: 12px;
  }
  
  .progress-cell-responsive {
    min-height: 50px;
    gap: 2px;
  }
  
  .completion-input {
    width: 40px !important;
  }
  
  .completion-input .el-input__inner {
    font-size: 10px;
    height: 20px;
    line-height: 20px;
    padding: 1px 2px;
  }
  
  .completed-weight-responsive {
    font-size: 9px;
  }
  
  .date-header {
    font-size: 9px;
    padding: 2px 0;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 2px;
  }
  
  .action-buttons .el-button {
    font-size: 10px;
    padding: 2px 4px;
    min-width: 60px;
  }
  
  .total-row {
    min-width: 600px;
    font-size: 11px;
    padding: 6px 12px;
  }
  
  .phase-stats-container {
    flex-direction: column;
    gap: 12px;
  }
  
  .phase-stats-period {
    min-width: auto;
    max-width: none;
  }
  
  .period-header {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
  
  .phase-stat-item {
    font-size: 11px;
  }
}

/* 小屏幕 (手机横屏/平板竖屏) */
@media (min-width: 481px) and (max-width: 768px) {
  .timeline-container {
    padding: 15px;
  }
  
  .header {
    flex-direction: column;
    gap: 20px;
  }
  
  .header-actions {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .header-actions .el-button {
    flex: 1;
    min-width: 140px;
  }
  
  .search-section {
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .search-input {
    flex: 1;
    min-width: 200px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .table-actions {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .table-actions .el-button {
    flex: 1;
    min-width: 150px;
  }
  
  .responsive-table {
    min-width: 700px;
  }
  
  .progress-cell-responsive {
    min-height: 55px;
  }
  
  .completion-input {
    width: 42px !important;
  }
  
  .completion-input .el-input__inner {
    font-size: 11px;
    height: 22px;
    line-height: 22px;
  }
  
  .completed-weight-responsive {
    font-size: 10px;
  }
  
  .action-buttons {
    gap: 3px;
  }
  
  .action-buttons .el-button {
    font-size: 11px;
    padding: 3px 6px;
  }
  
  .total-row {
    min-width: 700px;
    font-size: 12px;
  }
  
  .phase-stats-container {
    gap: 16px;
  }
  
  .phase-stats-period {
    min-width: 250px;
  }
}

/* 中等屏幕 (平板横屏/小桌面) */
@media (min-width: 769px) and (max-width: 1024px) {
  .timeline-container {
    padding: 20px;
  }
  
  .header {
    gap: 20px;
  }
  
  .header-actions {
    gap: 12px;
  }
  
  .header-actions .el-button {
    padding: 10px 16px;
  }
  
  .search-section {
    gap: 16px;
  }
  
  .table-actions {
    gap: 12px;
  }
  
  .responsive-table {
    min-width: 750px;
  }
  
  .progress-cell-responsive {
    min-height: 58px;
  }
  
  .completion-input {
    width: 44px !important;
  }
  
  .completion-input .el-input__inner {
    font-size: 11px;
    height: 23px;
    line-height: 23px;
  }
  
  .action-buttons {
    gap: 4px;
  }
  
  .action-buttons .el-button {
    font-size: 12px;
    padding: 4px 8px;
  }
  
  .total-row {
    min-width: 750px;
  }
  
  .phase-stats-container {
    gap: 18px;
  }
  
  .phase-stats-period {
    min-width: 280px;
  }
}

/* 大屏幕 (桌面) */
@media (min-width: 1025px) and (max-width: 1440px) {
  .timeline-container {
    padding: 24px;
  }
  
  .header {
    gap: 24px;
  }
  
  .header-actions {
    gap: 16px;
  }
  
  .search-section {
    gap: 20px;
  }
  
  .table-actions {
    gap: 16px;
  }
  
  .responsive-table {
    min-width: 800px;
  }
  
  .progress-cell-responsive {
    min-height: 60px;
  }
  
  .completion-input {
    width: 45px !important;
  }
  
  .action-buttons {
    gap: 4px;
  }
  
  .action-buttons .el-button {
    font-size: 12px;
    padding: 4px 8px;
  }
  
  .total-row {
    min-width: 800px;
  }
  
  .phase-stats-container {
    gap: 20px;
  }
  
  .phase-stats-period {
    min-width: 300px;
  }
}

/* 超大屏幕 (大桌面/4K) */
@media (min-width: 1441px) {
  .timeline-container {
    padding: 32px;
    max-width: 1800px;
    margin: 0 auto;
  }
  
  .header {
    gap: 32px;
  }
  
  .header-actions {
    gap: 20px;
  }
  
  .header-actions .el-button {
    padding: 12px 24px;
    font-size: 16px;
  }
  
  .page-title {
    font-size: 28px;
  }
  
  .description {
    font-size: 16px;
  }
  
  .search-section {
    gap: 24px;
  }
  
  .table-actions {
    gap: 20px;
  }
  
  .table-actions .el-button {
    padding: 12px 20px;
    font-size: 16px;
  }
  
  .responsive-table {
    min-width: 900px;
    font-size: 16px;
  }
  
  .progress-cell-responsive {
    min-height: 65px;
  }
  
  .completion-input {
    width: 50px !important;
  }
  
  .completion-input .el-input__inner {
    font-size: 13px;
    height: 26px;
    line-height: 26px;
  }
  
  .completed-weight-responsive {
    font-size: 12px;
  }
  
  .date-header {
    font-size: 12px;
  }
  
  .action-buttons {
    gap: 6px;
  }
  
  .action-buttons .el-button {
    font-size: 14px;
    padding: 6px 12px;
  }
  
  .total-row {
    min-width: 900px;
    font-size: 15px;
    padding: 12px 20px;
  }
  
  .phase-stats-container {
    gap: 24px;
  }
  
  .phase-stats-period {
    min-width: 350px;
    padding: 16px;
  }
  
  .period-header {
    font-size: 16px;
  }
  
  .phase-stat-item {
    font-size: 14px;
  }
}

/* 横屏模式优化 */
@media (orientation: landscape) and (max-height: 600px) {
  .timeline-container {
    padding: 10px;
  }
  
  .header {
    margin-bottom: 16px;
    padding-bottom: 12px;
  }
  
  .search-section {
    margin-bottom: 12px;
  }
  
  .schedule-table-section {
    margin-bottom: 20px;
  }
  
  .progress-cell-responsive {
    min-height: 45px;
  }
  
  .completion-input .el-input__inner {
    height: 20px;
    line-height: 20px;
  }
  
  .phase-stats-section {
    margin-top: 16px;
    padding: 12px;
  }
  
  .phase-stats-container {
    gap: 12px;
  }
  
  .phase-stats-period {
    padding: 8px;
  }
}

/* 高分辨率屏幕优化 */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .timeline-container {
    font-smooth: antialiased;
    -webkit-font-smoothing: antialiased;
  }
  
  .el-button {
    border-radius: 6px;
  }
  
  .el-table {
    border-radius: 8px;
  }
}

/* 打印样式优化 */
@media print {
  .timeline-container {
    padding: 0;
    background: white;
  }
  
  .header-actions,
  .table-actions,
  .action-buttons {
    display: none;
  }
  
  .responsive-table {
    min-width: auto;
    width: 100%;
  }
  
  .progress-cell-responsive {
    min-height: auto;
  }
  
  .completion-input {
    border: 1px solid #ccc;
    background: white;
  }
  
  .phase-stats-section {
    break-inside: avoid;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .timeline-container {
    background: #1a1a1a;
  }
  
  .timeline-card {
    background: #2d2d2d;
    border-color: #404040;
  }
  
  .page-title {
    color: #e0e0e0;
  }
  
  .description {
    color: #a0a0a0;
  }
  
  .total-row {
    background: #2a2a2a;
    border-color: #404040;
  }
  
  .phase-stats-section {
    background: #2a2a2a;
    border-color: #404040;
  }
  
  .phase-stats-period {
    background: #333333;
    border-color: #404040;
  }
}

/* 减少动画偏好 */
@media (prefers-reduced-motion: reduce) {
  .el-button,
  .el-input,
  .el-table {
    transition: none;
  }
  
  .el-loading-mask {
    animation: none;
  }
}

/* 高对比度模式 */
@media (prefers-contrast: high) {
  .timeline-container {
    border: 2px solid #000;
  }
  
  .el-button {
    border-width: 2px;
  }
  
  .el-table {
    border-width: 2px;
  }
  
  .progress-cell-responsive {
    border: 1px solid #000;
  }
}
</style> 